Share solution only loops for the '1'


  • 0
    S
    int hammingWeight(uint32_t n) {
        if (n == 0) return 0;
        
        int count = 0;
        while(n)
        {
            n = n & (n - 1);    // change the last bit of '1' to '0'
            ++ count;
        }
        return count;
    }

Log in to reply
 

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