문제

풀이

public int solution(int n) {
    int nCount = Integer.bitCount(n);

    while (true) {
        int nextCount = Integer.bitCount(++n);
        if (nCount == nextCount) break;
    }
    return n;
}

처음에는 이진수로 바꿨을 때의 1의 개수를 구하는 방식을 아래와 같이 구했었는데, 시간 초과가 떴다..

Integer.toBinaryString(n).replaceAll(”0”, “”).length()

그래서 검색해보니 Integer.bitCount(n) 라는 n의 이진 표현에서 1로 설정된 비트 수를 바로 계산해주는 내장메서드가 있어서 이를 사용했다.

어떤 메커니즘인지 뜯어봤는데 비트연산을 몰라서 이해가 잘 되진 않았다.

비트연산에 대해서 공부해봐야겠다…