반응형
10 진수 숫자가 주어지고, 그 수를 1씩 증가시킨다.
처음 주어진 숫자를 2 진수로 바꿔주고 그 수를 구성하는 1의 개수를 구한다.
1씩 증가하는 수를 2 진수화 시킨다.
이 때, 2 진수에 구성되는 1의 개수가 같은 다음 수를 구하는 문제.
Integer 클래스의 bitCount() 메서드를 사용하면 간단하게 1인 비트 수를 셀 수 있다.
class Solution {
public int solution(int n) {
int num = Integer.bitCount(n);
int answer = n;
while (true) {
answer = answer + 1;
int cnt = Integer.bitCount(answer);
if (num == cnt) break;
}
return answer;
}
}
반응형
'Algorithm' 카테고리의 다른 글
K번째수_프로그래머스 (0) | 2024.02.29 |
---|---|
C++로 BigInteger 구현해보기 (0) | 2023.04.11 |
Algorithm - Merge Sort (병합 정렬) (0) | 2022.08.18 |
Algorithm - Sieve of Eratosthenes(소수판별 알고리즘) (0) | 2022.07.30 |
Algorithm - 크루스칼 알고리즘(Kruskal) (0) | 2022.07.21 |
댓글