mycode 不会。。。
输入是二进制。。。。我还以为十进制。。。。 00000001011 = 11
题意:
编写一个将(无符号)整数作为输入的函数,并返回该数字二进制表示中等于1的位数。
例如:输入1234,其二进制表示为10011010010,所以所要求实现函数的输出应该是5。
参考
1 移位+计数
class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ count = 0 while n > 0 : if(n&1) == 1: count = count+1 n>>=1 return count
2、
思路:用n&(n-1)来消去一个1 能循环多少次就是能消多少个1~
因为如果那个位置本身就是1的话,那么减去一除了最后一位会变以外,其他都不会变 1111-1=1110;如果最后一位是0;则最右的1变为0,它右边的全部都取反一次,左边不变,然后与原本自己作与能恢复,变回只变换了一位的数据。如1000-1=0111 0111&1000=0000 实际上只把其中最右的1变为0而已;所以他能循环多少次就有多少个1.
如x=0001101011000
x- 1 = 0001101010111 那么&之后,x右边第一个1的位置变为0,右边的0还是0,所以还是相当count一个1
class Solution: def NumberOf1(self, n): if n<0: n = n & 0xffffffff cnt = 0 while n: n = n&(n-1) cnt += 1 return cnt
def isPowerOfTwo(n): if n&(n-1): return False return True class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ if n==0: return 0 elif n<=2: return 1 if isPowerOfTwo(n): #说明二进制数有且仅有一个1啦,所以消去了一个1后,if为False return 1 else : c=0 for i in range(32): c+=n%2 #感觉就是看最低位是不是1 n=n>>1 return c
3
def hammingWeight(self, n): """ :type n: int :rtype: int """ return str(bin(n).replace("0b","")).count("1")
或者
return bin(n).count("1")
return len(bin(n).replace("0b","").replace("0",""))
leetcode-easy-others-191. Number of 1 Bits-NO
原文:https://www.cnblogs.com/rosyYY/p/11004268.html