class Solution: # @param n, an integer # @return an integer def hammingWeight(self, n): return 0 if n==0 else (n&1) + self.hammingWeight(n>>1)
can you explain it for a bit? I have a hard time understand it, as well as this bit operation. why does add them together yield the correct result?
As we konw, the problem want to count the number of 1 bits, we can use( n & 1) to check whether the lowest bit is 1 or not. For example, 5 binary representation '101',it has two 1 bits, firstly, (n&1) is true because the lowest bit is 1,and we let n=n>>1,it means n=n/2. or you can understand it as binary representation change to 10. secondly, n&1 is false,n>>=1 ,and n binary representation change to 1 ,lastly, n&1 is true,n>>=1 ,and n is zero.
I just use recursion to make my code simple and cool.