Java 3 liner -- Only iterates for 1 bits


  • 7
    C
    public int hammingWeight(int n) {
        int i;
        for(i=0;n!=0;i++, n&=(n-1));
        return i;
    }
    

    n &=(n-1)
    removes the smallest 1 bit in n.


  • 1
    R

    Actually I got this error:


    Input: 2147483648 (10000000000000000000000000000000)

    Output: 33

    Expected: 1


Log in to reply
 

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