Bit shifting solution using Java


  • 7
    Y

    I start by looking at each of the 32 bits for the int value and use 1 << i to check each bit for 1.

    public int hammingWeight(int n) {
        int count = 0;
        for(int i = 0; i < 32; i++) {
            if(((1 << i) & n) != 0) {
                count++;
            }
        }
        return count;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.