整数加法

题目描述
请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值