One most consise solution with complexity linear to the result

  • 1
    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            while (n != 0) {
                n &= (n-1);
            return count;

    Any suggestions? Thanks.

  • 2

    Interesting. It never would have occurred to me to take the bits off the front of the string (n &= (n - 1)) instead of the back (n >>>= 1). However, your solution ought to actually be a touch faster, since it only loops for 1 bits that are present instead of for all 32 bits. Thanks for sharing!

  • 0

    :) In the worst case, there will still be 32 loops. But basically the result is the same as the number of 1's.

Log in to reply

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