4-line naiiive c++ solution


  • 2
    M
    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int ans=0;
            while (n)
                ans += n&1, n=n>>1;
            return ans;
        }
    };

  • 0
    L

    What if n is equal to 10000000000000000000000000000000 (binary)?
    There's a way to execute the while only once :)


  • 0
    X

    class Solution {
    public:
    int hammingWeight(uint32_t n) {

        int count=0;
        
        if (n==0)
            return 0;
        
        while (n&(n-1))
        {
            count++;
            n=n&(n-1);
        }
        
        count++;
        
        
        return count;
        
    }
    

    };


Log in to reply
 

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