题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。(这里只取前32位)
-2的补码为:先求-2的反码 10000.。。10 -》 11111.。。01
再求补码,即反码末尾加1:111.。。10
方法1:
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def NumberOf1(self, n): 4 count=0 5 n = n&0xFFFFFFFF #python 该数前面有多少位咱也不了解,截取32位就可以了 6 for i in str(bin(n)): 7 if i == '1': 8 count+=1 9 return count
方法2:
# -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): count = 0 for i in range(32): mask = 1<<i if mask & n!=0: count+=1 return count
方法3:
1 class Solution: 2 def NumberOf1(self, n): 3 count=0 4 n = n&0xFFFFFFFF 5 while n>0: 6 n = n&(n-1) 7 count+=1 8 return count
2019-12-02 09:51:36