当前位置 博文首页 > 中流击水,浪遏飞舟:一题多解&&剑指 Offer 15. 二进制
return __builtin_popcount(n);
bistset的简单用法
return bitset<32>(n).count();
循环检查1的个数(力扣官方题解
int ret = 0;
for (int i = 0; i < 32; i++) {
if (n & (1 << i)) {
ret++;
}
}
return ret;
/*
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/number-of-1-bits/solution/wei-1de-ge-shu-by-leetcode-solution-jnwf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
Brian Kernighan算法
去掉n末尾的1(力扣官方题解
int ret = 0;
while (n) {
n &= n - 1;
ret++;
}
return ret;
/*
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/number-of-1-bits/solution/wei-1de-ge-shu-by-leetcode-solution-jnwf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
除k取余法(评论区题解
int ans=0;
while(n)
{
ans+=n%2;
n>>=1;
}
return ans;
循环检查n的1(评论区题解
int ans=0;
while(n)
{
ans+=n&1;
n>>=1;
}
return ans;
注:以上全是看leecode题解整理的,学习思想。
cs