📖Algorithm/Simulation, Math
자바 [Programmers] 2단계 - 다음 큰 숫자
구동엽
2024. 11. 28. 16:10
class Solution {
public int solution(int n) {
int answer = 0;
String nBinaryCount = Integer.toBinaryString(n);
nBinaryCount = nBinaryCount.replace("0","");
int nCount = nBinaryCount.length();
while(true){
int temp = ++n;
String tempBinaryCount = Integer.toBinaryString(temp);
tempBinaryCount = tempBinaryCount.replace("0","");
int tempCount = tempBinaryCount.length();
if(nCount == tempCount){
answer = temp;
break;
}
}
return answer;
}
}
1. 먼저 n값에 대해 2진수 변환 후 0을 제외하여 길이를 구한다.
2. 무한 loop를 통해 n값 보다 큰 수에 대해 똑같이 2진수 변환 후 0을 제외하여 길이를 구한다.
3. 길이를 비교하여 같으면 break;