题目描述
请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回error
输入描述:
输入为一行,包含两个字符串,字符串的长度在[1,100]。
输出描述:
输出为一行。合法情况输出相加结果,非法情况输出error
示例1
输入
123 123
abd 123
输出
246
Error
思路
从两个字符串的后面开始遍历,这就像整数的加法一样从后面开始先加,计算完后再反过来输出就行了
#include<bits/stdc++.h>
using namespace std;
bool isshu(string s){
for(int i= 0; i< s.length(); i++){
if(!isdigit(s[i]))//判断是否是数字元素
{
cout<<"error"<<endl;
return 0;
}
}
return 1;
}
int main(){
string str, st;
while(cin>>str>>st){
if(isshu(str)&&isshu(st)){//两个字符串都合法再进行下面的操作
string s;
int count= 0;
int i= str.length()- 1;
int j= st.length()- 1;
while(i>= 0&&j>= 0){
s+= ((str[i--]- '0'+ st[j--]- '0'+count)%10+ '0');
//两个数相应位先加
count= (str[i+ 1]- '0'+ st[j+ 1]- '0')/10;
//相应位相加超过10进1
}
while(i>= 0){
s+= ((str[i--]- '0'+count)%10+ '0');
count= (str[i+ 1]- '0')/10;
}
while(j>= 0){
s+= ((s[j--]- '0'+ count)%10+ '0');
count= (s[j+ 1]- '0')/10;
}
if(count)//不要忘了这一步
s+= (count+ '0');
reverse(s.begin(), s.end());//将字符串反过来
cout<<s<<endl;
}
}
return 0;
}