Algorithm/수학
[프로그래머스 lv2] 다음 큰 숫자
09009
2023. 11. 14. 15:37
문제 보기
https://school.programmers.co.kr/learn/courses/30/lessons/12911
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 해결
Integer.toBinaryString()을 이용한 후 String.replaceAll("0","")으로 0을 지운 후 1의 개수를 비교하려 했으나 효율성이 실패가 떴다.
Integer.bitCount(int n) : 주어진 정수 n의 true bit (1)의 개수를 찾아주는 역할을 한다. 이 메서드로 문제를 해결한다.
소스 코드
import java.util.*;
class Solution {
public int solution(int n) {
int answer = 0;
int bitCnt = Integer.bitCount(n);
int cnt;
while (true) {
n++;
cnt = Integer.bitCount(n);
if (cnt == bitCnt) {
answer = n;
break;
}
}
return answer;
}
}