二进制表示形式
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:我在这里有一个不正确的解决方案,将其删除。感谢评论指出。
相关文章:
- 浮点数为 32 位和 64 位二进制表示形式
- 如何将uint8_t的二进制表示形式读取为数字
- 二进制表示,如何获得"相关位"?
- C++ 如何以二进制格式表示字符串?
- 编译器C++如何在二进制代码中表示整数
- 了解浮点数的二进制表示形式
- 如何在 mfc c++ 中流式传输.zip文件夹的二进制表示形式
- 浮点逆二进制表示
- 以C++显示浮点类型的二进制表示形式
- 如何使用C 将二进制数字的字符串转换为其签名的十进制表示
- 在二进制表示中将二进制 std::string 转换为 int
- 如何在没有循环的二进制数字表示中只计算1位
- 如何在计算机内存中打印长双重表示的二进制表示
- 将uint8_t转换为其二进制表示
- 如何在C++中操作和表示二进制数
- 如何在C++中表示二进制字节数组数据
- 如何在编程语言中表示二进制字段
- 如何在C++中表示二进制数(用于霍夫曼编码器)
- 如何在表示二进制文件的字符串中查找整数
- 将表示二进制的字符串转换为表示等效十六进制的字符串