leetcode-191-位1的个数
题目描述;

第一次提交:
class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ n = str(bin(n)) count = 0 for i in n: if i == '1': count += 1 return count
另:
return str(bin(n)).count('1')
方法二:O(1)O(1)

class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ count = 0 while n!=0: count += 1 n &= n-1 return count
方法三:
class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ count = 0 while n: count += n&1 n >>= 1 return count
浙公网安备 33010602011771号