A straightforward solution


  • 2
    L
    public int HammingWeight(uint n) {
        int count = 0;
        while(n != 0)
        {
            count += (int)(n & 1);
            n >>= 1;
        }
        return count;
    }

  • 1
    S

    +1. Added some comments:

    public int HammingWeight(uint n) {
        int numOnes = 0;
        while (n != 0) {
            // ex:       00000000000000000000000000001011 and'd with
            //           00000000000000000000000000000001
            // will be   00000000000000000000000000000001
            // so numOnes will increment by 1.
            numOnes += (int)(n & 1);
            // right-shift assignment. shifts n's bits to the right by 1 and stores it in n.
            n >>= 1;
        }
        return numOnes;
    }

  • 0
    E
    This post is deleted!

  • 0
    W

    Why "(int)"? The result of(n&1) would be either 0 or 1, which means it's already an integer.


Log in to reply
 

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