Concise Java Solution x & (x-1)


  • 21
    S

    x & (x-1) helps to remove right most 1 for x. For reference, see Bit Hacks

    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 & (n-1);
                count++;
            }
            return count;
        }
    }
    

Log in to reply
 

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