题目:给定一个整数,输出这个整数的二进制表示中1的个数。例如:给定整数7,其二进制表示为111,结果为3。
分析:
(1)移位法。位操作。首先,判断这个数的最后以为是否为1,如果为1,那么计算器加1,然后通过右移丢弃掉最后一位,循环执行该操作直到这个数等于0位置。在判断二进制表示的最后一位是否为1时,可以采用与运算来达到这个目的。
code1:
def countOnes1(x):
count = 0
while x > 0:
if x & 1 == 1: # 判断最后一位是否为1
count += 1
x >>= 1 # 移位丢掉最后一位
return count
c = countOnes1(x)
print("binary from of 1234 is {0}".format(bin(x)))
print("binary from of 1234 is {0}".format(c))
(2)与操作。给定一个数n,每进行一次n&(n-1)计算,其结果中都会少了一位1,而且是最后一位。
code:
def countOnes2(x):
count = 0
while x > 0:
count += 1
x &= (x - 1)
return count
x = 1234
c = countOnes2(x)
print("binary from of 1234 is {0}".format(bin(x)))
print("binary from of 1234 is {0}".format(c))