因为写了一段错误的代码,结果也能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