C solution, only need 1ms!

  • 6

    int hammingWeight(uint32_t n) {

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


  • 8

    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.