Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

https://leetcode.cn/problems/number-of-1-bits/description/

Q

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

A

移位,检查每一位是不是1

class Solution
{
public:
    int hammingWeight(uint32_t n)
    {
        int cnt = 0;
        for (int i = 0; i < 32; ++i)
        {
            if (n & 1u)
                ++cnt;
            n >>= 1;
        }
        return cnt;
    }
};

不断将最低位的1设置为0:

n &= (n - 1);将n的最低位1设置成0,其他不变

n-1将n的最低位1(之前的位都是0)之前的位变成1,将n的最低位1变成0

class Solution
{
public:
    int hammingWeight(uint32_t n)
    {
        int cnt = 0;
        while (n)
        {
            ++cnt; 
            n &= (n - 1); // 将最低位的1设置为0
        }
        return cnt;
    }
};

评论