因为写了一段错误的代码,结果也能AC,比较有趣就记下来了
class Solution:
# @param num: an integer
# @return: an integer, the number of ones in num
def countOnes(self, num):
# write your code here
if num < 0:
num = num + 4294967296
a, count = '{0:b}'.format(num), 0
for i in a:
if i == "1":
count += 1
return count
下面是看了参考的网上的位运算做的:
count = 0;
for i in range(0,32):
if num & 1:
count += 1
num = num >> 1
return count
本文介绍了一种有趣的计数整数中1的位数的方法。即使输入的整数是负数,该方法也能正确计算其二进制表示中1的数量。通过两种不同的实现方式展示了这一过程:一种使用字符串转换,另一种采用位运算。
298

被折叠的 条评论
为什么被折叠?



