二进制表示形式

binary representation

本文关键字:表示 二进制      更新时间:2023-10-16

例如,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:我在这里有一个不正确的解决方案,将其删除。感谢评论指出。