Super simple Java solution with explanation.


  • 1

    We can use such a bit manipulation to get all "1"s from a integer:

    while(a != 0) {  
        int p = a & -a; // p 就是取出来的 1 (P is the "1" we got from a)
        a ^= p; // remove that "1"
        Do something with p; 
    }
    

    There is also an interesting post(中文的) about how to use bit manipulation like the method above to speed up N-queen problem (the fastest way I know).

    The solution of this question is :

    public int hammingWeight(int n) {
            int count = 0;
            while (n != 0) {
                int p = n & -n;
                n ^= p;
                count++;
            }
            return count;
        }
    

Log in to reply
 

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