One line and clearly solution(JAVA)


  • 7

    Each time n & (n - 1) reduce an '1', here is the code:

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            return n == 0 ? 0 : 1 + hammingWeight(n & (n - 1));
        }
    }

Log in to reply
 

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