题目详细链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
解法1:
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
unsigned int flag = 1;
while (flag) {
if (flag & n) {
cnt++;
}
flag <<= 1;
}
return cnt;
}
};
解法2:
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt =0;
while (n) {
cnt++;
n = (n-1) & n;
}
return cnt;
}
};
作者:NorthCity1984
出处:https://grimoire.cn/offer/er-jin-zhi-zhong-1de-ge-shu-lcof.html
版权:本文《剑指 Offer 15. 二进制中1的个数》版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
出处:https://grimoire.cn/offer/er-jin-zhi-zhong-1de-ge-shu-lcof.html
版权:本文《剑指 Offer 15. 二进制中1的个数》版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任