카테고리 없음
[프로그래머스] 다음 큰 숫자(JAVA)
밍래그로프
2022. 4. 7. 21:47
문제는 이렇다
Integer.toBinaryString 을 이용하여 이진수를 문자열화 하면 쉽게 풀리겠구나 하고 풀었다.
다음은 내가 푼 답이다.
package algorithm.programmers.level2;
public class nextMaxNumber {
public int solution(int n) {
int answer = n+1;
int nOneCount = oneCount(Integer.toBinaryString(n));
String resultBinary;
int resultOneCount = 0;
while(true){
resultBinary = Integer.toBinaryString(answer);
resultOneCount = oneCount(resultBinary);
if(nOneCount == resultOneCount){
return answer;
}
answer++;
}
}
public int oneCount(String s){
int oneCount = 0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '1' ){
oneCount++;
}
}
return oneCount;
}
}