Ssup2 Blog logo Ssup2 Blog

Problem

Solution 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
    public int solution(int n) {
        // Get n's one count
        int nBinOneCount = getOneCount(n);
        
        // Find n's next
        for (int i = n + 1; i <= 1000000; i++) {
            if (nBinOneCount == getOneCount(i)) {
                return i;
            }
        }
        
        // Not found
        return 0;
    }
    
    private int getOneCount(int n) {
        String nBin = Integer.toBinaryString(n);
        int oneCount = 0;
        for (int i = 0; i < nBin.length(); i++) {
            if (nBin.charAt(i) == '1') {
                oneCount++;
            }
        }
        return oneCount;
    }
}
Solution 1