C solution ,O(m) time, 1ms


  • 4
    A
    int hammingWeight(uint32_t n) {
        int res = 0;
        while( n )
        {
            n &= n - 1;
            res++;
        }
        return res;
    }

  • 1
    A
    int hammingWeight(uint32_t n) {
        int res = 0;
        int i = 0;
        while( i++ < 32 )
        {
              res += n & 1;
              n >>= 1;
        }
        return res;
    }

Log in to reply
 

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