[英]binary representation
例如sum(6)必须返回2,因为6的二进制版本是110
不确定逻辑是否正确。
int sum(int n)
{
int count = 0;
while(n)
{
count += n & 1;
n >>= 1;
}
return count;
}
int main(){
int n = 9001;
cout << “The sum of bits for number “ << n << “is” << sum(n) << endl;
retun 0;
}
与以往一样,解决这些问题的最佳方法是使用标准库。 你们都研究过标准库中可用的工具吧?
;-)
#include <iostream>
#include <bitset>
template<class T>
size_t bits_in(T t)
{
return std::bitset<sizeof(t) * 8>(t).count();
}
int main()
{
using namespace std;
int i = 6;
cout << "bits in " << i << " : " << bits_in(i) << endl;
long l = 6353737;
cout << "bits in " << l << " : " << bits_in(l) << endl;
return 0;
}
预期输出:
bits in 6 : 2
bits in 6353737 : 11
int sum(int n)
{
int count = 0;
if (0 != n)
{
while(++count, n &= (n - 1));
}
return count;
}
速度很快,因为它每 1 位只循环一次。
如果您使用 GCC 作为编译器,请查看内置的__builtin_popcount()
。 它以二进制表示形式返回 1 的数量。
请参阅此处了解更多信息。
编辑 2:我在这里有一个不正确的解决方案,将其删除。 感谢评论指出它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.