Solution using Java >>> operator


  • 4
    G
    public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        for(int i = 0; i < 32; i++) {
            if((n & 1) == 1) count++;
            n = n >>> 1;
        }
        return count;
    }
    

    }


  • 0
    L

    Do "n = n & (n - 1)" instead to set the rightmost 1 bit to zero.


Log in to reply
 

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