Problem Definition:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
Solution:
基本方法,Python实现,直观到不好意思。
1 def hammingWeight(n): 2 count=0 3 count+=(n%2) 4 b=n/2 5 while b!=0: 6 count+=(b%2) 7 b=b/2 8 return count
但是上面的代码不够“Python”,应该这么的:(reference1)(reference2)
def hammingWeight(n): return (bin(n)[2:]).count('1')
然而用位操作是很方便的:
1 def hammingWeight(n): 2 count=0 3 count+=(n&1) 4 b=n>>1 5 while b!=0: 6 count+=(b&1) 7 b=b>>1 8 return count
或者,这样:
1 def hammingWeight(n): 2 n=((n & 0xAAAAAAAA)>>1)+(n & 0x55555555) 3 n=((n & 0xCCCCCCCC)>>2)+(n & 0x33333333) 4 n=((n & 0xF0F0F0F0)>>4)+(n & 0x0F0F0F0F) 5 n=((n & 0xFF00FF00)>>8)+(n & 0x00FF00FF) 6 n=((n & 0xFFFF0000)>>16)+(n & 0x0000FFFF) 7 return n