Java solution, 2 methods


  • 2
    H
    // method1
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int x = 0;
        while (n != 0) {
           x += (n - ((n >>> 1) << 1));
           n = n >>> 1;
        }
        return x;
    }
    

    // method2
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int x = 0;
        while (n != 0) {
           x += (n & 1);
           n = n >>> 1;
        }
        return x;
    }

Log in to reply
 

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