Easy Java solution


  • 3
    I

    The trick is you check the last bit of n by performing n & 1 and add it to result. Then perform unsigned right shift >>> until n becomes 0.

    public int hammingWeight(int n) {
       int result = 0;
       while(n != 0) { 
          result += (n & 1);
          n >>>= 1;
       }
       return result;
    }

  • 0
    S
    This post is deleted!

Log in to reply
 

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