문제

문제풀이
public int solution(int n) { //다음 큰 숫자
int count = 0;
int match = 0;
int num = n;
String str = Integer.toBinaryString(n); //이진수로 변경
for(char x : str.toCharArray()){ //1이 들어간 갯수를 count
if(x == '1'){
count++;
}
}
Loop1:
while(true){
match = 0;
num++; //n의 다음수부터 대입
String str2 = Integer.toBinaryString(num); //이진수로 변경
for(char z : str2.toCharArray()){ //1이 들어간 횟수를 count
if(z == '1'){
match++;
}
}
if(match == count){ //match와 count의 갯수가 같으면 while문 break
break Loop1;
}
}
return num; //그때의 num값 반환
}
원래는 이렇게 복잡하게 풀었으나 다른 사람의 글을 보니 bitCount()라는 메서드를 써서 쉽게 풀었다....
bitCount()는 이진수로 바꾼뒤 거기에서 1의 갯수를 카운트하는 메서드이다.
그래서 다른 분의 풀이코드를 보면
public int nextBigNumber(int n)
{
int a = Integer.bitCount(n);
int compare = n+1;
while(true) {
if(Integer.bitCount(compare)==a)
break;
compare++;
}
return compare;
}
이런식으로 풀었다... 주석을 달지 않아도 이해가 쉬울 정도로 간단하다!
'프로그래머스 > Level 2' 카테고리의 다른 글
| [프로그래머스][Level2][Java] 프린터 (0) | 2022.03.18 |
|---|---|
| [프로그래머스][Level2][Java] 124 나라의 숫자 (0) | 2022.03.12 |
| [프로그래머스][Level2][Java] 땅따먹기 (0) | 2022.03.10 |
| [프로그래머스][Level2][Java] 숫자의 표현 (0) | 2022.03.08 |
| [프로그래머스][Level2][Java] 최솟값 만들기 (0) | 2022.03.07 |