[LeetCode by python] Number of 1 Bits

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.

下面是四种算法:

 1 #coding=utf-8
 2 '''
 3 Created on 2015��3��26��
 4 
 5 @author: zxf520
 6 '''
 7 class Solution:
 8     def hammingWeight1(self, n):
 9         count=0
10         while n:
11             count+=(n&1)
12             n>>=1
13         return count
14     def hammingWeight2(self,n):
15         count=0
16         while n:
17             if n%2==1:
18                 count=count+1
19             n/=2
20         return count
21     def hammingWeight3(self, n):
22         count=0
23         while n:
24             count=count+1
25             n&=(n-1)
26         return count
27     def hammingWeight4(self,n):  #分治法
28         n=(n&0x55555555)+((n>>1)&0x55555555)
29         n=(n&0x33333333) + ((n>>2)&0x33333333)
30         n=(n&0x0f0f0f0f) + ((n>>4)&0x0f0f0f0f)
31         n=(n&0x00ff00ff) + ((n>>8)&0x00ff00ff)
32         n=(n&0x0000ffff) + ((n>>16)&0x0000ffff)
33         return n
34 
35 if __name__ == '__main__':
36     s=Solution()
37     n=raw_input("请输入一个整数:")
38     #y=s.hammingWeight(int(n))
39     y=s.hammingWeight4(int(n))
40     print y

 

下面图片来着维基百科:赞一个!

posted @ 2015-03-26 14:43  编程风  阅读(232)  评论(0编辑  收藏  举报