문제풀이/프로그래머스
[Python, JAVA] 프로그래머스 - 다음 큰 숫자
그적
2022. 9. 26. 21:47
(문제설명 / 제한사항)

(풀이 방법)
1) n을 1씩 증가해가면서 이진수로 변환한다.
2) 1의 개수가 동일하면 while문을 빠져나온다.
3) 최종 n 값을 리턴해준다.
(코드 - Python)
def solution(n):
answer = 0
one_count = bin(n)[2:].count('1')
while True:
n += 1
if bin(n)[2:].count('1') == one_count:
break
answer = int(n)
return answer
(코드 - JAVA)
class Solution {
public int solution(int n) {
int answer = 0;
int one_count = 0;
String binary = Integer.toBinaryString(n);
for(int i=0; i<binary.length(); i++)
if(binary.charAt(i) == '1') one_count++;
while(true){
n++;
int tmp_count = 0;
String tmp_binary = Integer.toBinaryString(n);
for(int i=0; i<tmp_binary.length(); i++)
if(tmp_binary.charAt(i) == '1') tmp_count++;
if(one_count == tmp_count) break;
}
answer = n;
return answer;
}
}