字符串加法问题:
1.当输入的二进制字符串长度不相等时,较短字符串前面补0,使得两字符串长度相等;
2.从后向前遍历字符串a和字符串b(此时两字符串长度相等):
****此时根据字符串a和字符串b中具体对应的字符分情况讨论:
if (a[i]=='0') && (b[i]=='0')
if(前一个相加产生进位)
result += '1';
进位标志为false;
else
result +='0';
进位标志为false;
else if (a[i]=='0') && (b[i]=='1')
...
else if (a[i]=='1') && (b[i]=='0')
...
else
...3.若此时进位标志为true,则 result += '1'
4.上述计算的result为逆序结果,此时逆序输出即为所求.
下面为代码实现:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a,b;
cin>>a>>b;//输入字符串a和b
//如果a与b字符串长度不相等
int aLength=a.size();
int bLength=b.size();
while(aLength > bLength){
b = '0'+b;
bLength++;
}
while(aLength < bLength){
a = '0'+a;
aLength++;
}
//此时,字符串a与字符串b长度相等
bool over_flag=false;
string result;
for(int i=aLength-1; i>=0; i--){
if((a[i]=='0') && (b[i]=='0')){
if(over_flag == true){
result += '1';
}
else{
result += '0';
}
over_flag=false;
}
else if((a[i]=='0') && (b[i]=='1')){
if(over_flag == true){
result += '0';
over_flag=true;
}
else{
result += '1';
over_flag=false;
}
}
else if((a[i]=='1') && (b[i]=='0')){
if(over_flag == true){
result += '0';
over_flag=true;
}
else{
result += '1';
over_flag=false;
}
}
else{ //a[i]=='1 && b[i]=='1'
if(over_flag == true){
result += '1';
}
else{
result += '0';
}
over_flag=true;
}
}
if(over_flag == true){
result += '1';
}
for(int j=result.size()-1; j>=0; j--){
cout<<result[j];
}
return 0;
}
京公网安备 11010502036488号