难度:容易
1. Description
2. Solution
- python
class Solution:
"""
@param: num: An integer
@return: An integer
"""
def countOnes(self, num):
# write your code here
if num<0:
num = 2**31+num
res = 1
else:
res = 0
while num>0:
if num%2!=0:
res+=1
num = num//2
return res
更好的方法,使用位操作。
class Solution:
"""
@param: num: An integer
@return: An integer
"""
def countOnes(self, num):
# write your code here
res = 0
for i in range(32):
res += num & 1
num >>= 1
return res