【题目】
编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
来源:leetcode
链接:https://leetcode-cn.com/problems/number-of-1-bits/
【示例1】
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。
【示例2】
输入:00000000000000000000000010000000
输出:1
【示例3】
输入:11111111111111111111111111111101
输出:31
【代码】
其实出题者本意不是让你用这种方式,虽然能做出来
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt=0;
while(n){
if(n%2)
cnt++;
n/=2;
}
return cnt;
}
};
【位运算解法】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :6.1 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
int hammingWeight(uint32_t n) {
int m=0;
for(;n;m++)
n&=n-1;
return m;
}
};
【知识点】
关于位运算,任意数字n,对其进行n&(n-1)操作,都会将n的最后一个数字变为0
【逐位判断】
执行用时 :4 ms, 在所有 C++ 提交中击败了58.01% 的用户
内存消耗 :6 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
int hammingWeight(uint32_t n) {
int mask=1;
int cnt=0;
for(int i=0;i<32;i++){
if(n&mask)
cnt++;
n>>=1;
}
return cnt;
}
};