gpt4 book ai didi

c++ - 添加 2 个二进制数作为字符串,C++

转载 作者:行者123 更新时间:2023-11-28 06:23:45 25 4
gpt4 key购买 nike

我在添加 2 个二进制数时遇到问题。我想以字符串的形式执行此操作,因此如果它们的长度不同,我将“0”连接到较短字符串的开头。首先,我不知道为什么,但我需要衬底然后添加“0”(没有它,它根本不起作用)。

#include <iostream>
using namespace std;


string add( string no1, string no2 );


int equalizer(string no1, string no2)
{
int len1 = no1.length();
int len2 = no2.length();
if (len1 < len2)
{
for (int i = 0 ; i < len2 - len1 ; i++)
{

no1 = '0' + no1;
}
return len2;
}
else if (len1 >= len2)
{
for (int i = 0 ; i < len1 - len2 ; i++)
{

no2 = '0' + no2;
}
return len1; // If len1 >= len2
}

}


string add( string no1, string no2 )
{
string result="";


int length = equalizer(no1, no2);

int carry = 0;


for (int i = length-1 ; i >= 0 ; i--)
{
int bit1 = no1.at(i) - '0';
int bit2 = no2.at(i) - '0';

// boolean expression for sum of 3 bits
int sum = (bit1 ^ bit2 ^ carry)+'0';

result = (char)sum + result;

// boolean expression for 3-bit addition
carry = (bit1 & bit2) | (bit2 & carry) | (bit1 & carry);
}

// if overflow, then add a leading 1
if (carry)
{


result = '1' + result;
}

return result;
}
bool check(string no1)
{
for(int i =0; i<no1.length(); i++)
{
if(no1.at(i)!=0 || no1.at(i)!=1)
{
cout << "not biniary! should contain only '0' and '1' "<< endl;
return false;
}
else
{
return true;
}
}
}
int main()
{
string no1;
string no2;
cout << "Welcome to program that add 2 biniary numbers!" << endl;
cout <<"Give first number " <<endl;
cin >> no1;
if(check(no1)==true)
{





cout <<"Give 2nd number" << endl;
cin >> no2;
check(no2);
cout << "Numbers are proper!" << endl;
add(no1,no2);
}
else
{
cout <<"End of program."<<endl;
}
return 0;
}

最佳答案

我不添加尾随零,而是在开头反转字符串:std::reverse(s1.begin(), s1.end())。然后我会从开始添加每个数字。 res[i] = s1[i] - s2[i] + '0'; 记得初始化 res 字符串,然后再反转回来!祝你好运!

关于c++ - 添加 2 个二进制数作为字符串,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28885721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com