Simple Java solution without bit shifting


  • 0
    M

    The solution relies on the fact that (n & n-1) takes out the least significant 1 from the bit pattern. We keep on doing this until we hit 0.
    To make this work for unsigned int, we first convert int to long as representative of unsigned int.

    public class Solution {
        public int hammingWeight(int n) {
            int count = 0;
            for(long l = n & 0x00000000ffffffffL; l > 0; l = (l & (l-1))){
                count++;
            }
            return count;
        }
    }
    

Log in to reply
 

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