对于这个程序,我将输入一个二进制数,它将转换为一个十进制数。最后,我想返回我输入的二进制数字中的数字数。例如,1001-4二进制digits.The输出的二进制数的数字总是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;
}发布于 2020-06-03 18:05:09
看起来你对无符号整数的选择是正确的。乘法中的带符号整数通常用保存的结果符号转换为正整数。
您可以节省一些时间的比特数据解决方案,因为价值测试不是免费的加‘和’没有进位延迟。当然,一些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
https://stackoverflow.com/questions/62179042
复制相似问题