c++ - 如何在不循环的情况下仅计算数字的二进制表示形式中的 1 位

标签 c++ c algorithm

假设我有两个数字(最小值和最大值)。 `

for example (0 and 9999999999)

最大值可能如此之大。现在我还有一些其他的号码。它可能介于最小和最大数量之间。 假设为 15。现在我需要做的是获取 15 的所有倍数(15,30,45 等等,直到达到最大数)。对于每个数字,我必须计算它们的二进制表示中有多少个 1 位。 例如,15有4个(因为它只有4个1位)。

问题是,我需要一个循环中的循环才能得到结果。第一个循环是获取该特定数字的所有倍数(在我们的示例中为 15),然后对于每个倍数,我需要另一个循环来仅计算 1 位。我的解决方案需要很多时间。这是我的做法。

unsigned long long int min = 0;
    unsigned long long int max = 99999999;
    unsigned long long int other_num = 15; 
    unsigned long long int count = 0;

    unsigned long long int other_num_helper = other_num;
    while(true){
        if(other_num_helper > max) break;
        for(int i=0;i<sizeof(int)*4;i++){
            int buff = other_num_helper & 1<<i;
            if(buff != 0) count++; //if bit is not 0 and is anything else, then it's 1bits.
        }

        other_num_helper+=other_num;

    }
    cout<<count<<endl;

最佳答案

查看 0 到 2^3 之间数字的位模式

000
001
010
011
100
101
110
111

你看到了什么?

每一位都是 1 的 4 倍。

如果概括一下,您会发现 0 到 2^n 之间的数字总共设置了 n*2^(n-1) 位。

我确信您可以将这个推理扩展到任意范围。

关于c++ - 如何在不循环的情况下仅计算数字的二进制表示形式中的 1 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54004394/

相关文章:

c++ - srand(time(0)) 和随机数生成

c++ - 在不知道名称的情况下打开文件

c++ - 宇宙飞船运算符(operator)的真实世界使用示例

c - 强制转换时截断指针

c - 我需要删除这个变量吗?

c++ - 使用着色器绘制多个对象 (GLEW)

c - strtok坏了吗?或者只是棘手?

algorithm - 该算法的大 O 表示法是什么?

python - 为什么在进行迭代时某些特定数字需要这么长时间

algorithm - 从数字列表中找到一对和的算法?