C solution, only need 1ms!


  • 6
    X


    int hammingWeight(uint32_t n) {

    int ret = 0;
    while (n) {
        if (n & 0x01)
            ret++;
        n >>= 1;
    }
    return ret;
    

    }


  • 8
    N

    The compiler will optimize it for sure, but you can actually write:

    ret += n&1;
    

    No need for an extra conditional jump.


Log in to reply
 

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