请实现一个函数,输入一个整数,输出该数二进制表示中1的个数。例如把9表示成二进制是1001,有2位是1。因此如果输入9,该函数输出2。

LeetCode

C++ 题解

把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0。那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。  
15 二进制中1的个数

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int counts = 0;
        while(n)
        {
            n &= (n-1);
            counts++;
        }
        
        return counts;
        
    }
};

python 题解

方法一

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0

        while n:
            n = n & (n-1)
            count += 1
        
        return count

方法二

bin函数可以准换int类型为二进制字符串:

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        
        return bin(n).count('1')

相关文章:

  • 2022-12-23
  • 2022-01-11
  • 2021-12-12
猜你喜欢
  • 2021-09-13
  • 2021-06-28
  • 2022-03-01
  • 2021-06-03
  • 2022-12-23
相关资源
相似解决方案