Programmers | 다음 큰 숫자 [LV2] (Java)
문제
풀이 1 : bitCount() 활용
Integer.bitCount는 정수를 매개변수로 넣었을 때 그 정수의 이진수에서 1의 개수를 반환한다.
1111 -> 4
public class Solution {
public int solution(int n) {
int cnt = Integer.bitCount(n);
for(int i = n+1; ; i++){
if (Integer.bitCount(i) == cnt) return i;
}
}
}
풀이 2 : bitCount() 대신 함수 구현
비트 연산을 통해 문제를 해결했다.
&, >> 연산자..
public class Solution {
public int solution(int n) {
int count = countOne(n);
for(int i = n+1; ; i++){
if(countOne(i) == count) return i;
}
}
public int countOne(int n) {
int cnt = 0;
while(n>0) {
if((n&1) == 1) cnt++;
n >>= 1;
}
return cnt;
}
}
풀이 3 : 이진수 구하기
public class Solution {
public int solution(int n){
int count = countOne(n);
while(countOne(++n) != count);
return n;
}
private int countOne(int n) {
String bin = Integer.toBinaryString(n);
int count = 0;
// 1번
for (int i = 0; i < bin.length(); i++) {
String b = bin.substring(i, i+1);
if (b.equals("1")) count++;
}
// 2번
// for(char ch : bin.toCharArray()) {
// if(ch == '1') count++;
// }
return count;
}
}
Author And Source
이 문제에 관하여(Programmers | 다음 큰 숫자 [LV2] (Java)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@omnireader0/Programmers-다음-큰-숫자-LV2-Java저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)