【问题标题】:Count the number of digits in a Binary计算二进制中的位数
【发布时间】:2020-06-03 17:29:34
【问题描述】:

对于这个程序,我将输入一个二进制数,它将转换为十进制数。最后,我想返回我输入的二进制数中的位数。例如,1001 - 4 二进制数。二进制数的位数输出始终为 0。我应该使用 size_type 吗?

#include<iostream>
#include<string>
#include<bitset>
#include<limits>
#include<algorithm>

using namespace std;
int multiply(int x);

int multiply(int x)
{
    if (x == 0)
    {
        return 1;
    }

    if (x == 1)
    {
        return 2;
    }

    else
    {
        return 2 * multiply(x - 1);
    }
}

int count_set_bit(int n) 
{
    int count = 0;
    while (n != 0) 
    {
        if (n & 1 == 1) 
        {
            count++;
        }
        n = n >> 1; 
    }
    return count;
}

int main()
{
    string binary;

    cout << "\n\tDualzahlen : ";
    cin >> binary;

    reverse(binary.begin(), binary.end());
    int sum = 0;
    int size = binary.size();
    for (int x = 0; x < size; x++)
    {
        if (binary[x] == '1')
        {
            sum = sum + multiply(x);
        }
    }
    cout << "\tDezimal : " << sum << endl;

    int n{};
    cout << "\tAnzahl der Stelle : " << count_set_bit(n) << endl;
}

【问题讨论】:

  • 二进制数的大小为binary.size()。不确定你想用int n{}; cout &lt;&lt; "\tAnzahl der Stelle : " &lt;&lt; count_set_bit(n) &lt;&lt; endl; 做什么,因为n 是零,你总是会得到零
  • 仔细查看参数nint n{}; -> count_set_bit(n) -> while (n != 0)。此时n 将具有什么价值? n 应该是什么?
  • 您的 count_set_bits 函数以二进制形式计算 1 的位数(因此对于 1001,结果为 2),而不是总位数。

标签: c++


【解决方案1】:

看起来你在无符号整数的正确轨道上。乘法中的有符号整数通常会使用保存的结果符号转换为正数。

您可以使用位数据解决方案节省一些时间,因为值测试不是免费的,而且“并且”没有进位延迟。当然,有些 CPU 的 ++ 速度可能比 += 1 快,但希望编译器知道如何使用它:

int bits( unsigned long num ){
    retVal = 0 ;

    while ( num ){
        retVal += ( num & 1 );
        num >>= 1 ;
    }

    return retVal ;
}

我记得 H-4201 一次乘以 2 位,使用可能是移位,可能是加法,可能是进位/借位,所以 0 不是加法,1 是加法,2 是移位和加法,3 是进位/借位加法(4 - 1)!那是在 IC 乘法被埋在电路和 ROM 中之前。 :D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多