· 1 min read

Blind 75 - Number of 1 Bits

Check if the last bit is 1 by (n&1). Do the right unsigned shift (logical shift >>>). Loop.

[Video]

[Problem explanation in English]

Return the number of binary ones. also known as hamming weight.

Link

Approaches

O(time) time; O(space) space; n lines

Check if the last bit is 1 by (n&1). Do the right unsigned shift (logical shift). Loop.

    public int hammingWeight(int n) {
        int count = 0;
        
        while(n!=0){
            count+=(n&1);
            n=n>>>1;
        }
        
        return count;
    }

Back to Blog