题目描述:统计二进制中1的位数。

题目链接:191. Number of 1 Bits

初步想法就是沿用上题190的思路,右移n,然后不断按位与操作来进行计数。

当然也可以用我以前面试的时候答的转成字符串哈哈哈~

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        ans = 0
        while(n):
            if((n&1)==1):
                ans += 1
            n >>= 1
        return ans

参考链接

191. Number of 1 Bits | 汉明重量几种解法

Leetcode 191. Number of 1 Bits

相关文章:

  • 2021-07-11
  • 2022-12-23
  • 2021-10-29
  • 2022-01-22
  • 2021-10-28
  • 2021-08-17
  • 2021-05-19
  • 2021-09-09
猜你喜欢
  • 2022-01-09
  • 2021-06-16
  • 2022-03-07
  • 2021-07-02
  • 2021-12-04
相关资源
相似解决方案