计算A+B(高精度加法)

28 篇文章 0 订阅

计算A+B

题目链接
在一行中给出一个字符串,请判断是否满足A + B格式,如果满足,输出计算结果,否则输出"skipped"。
此处A,B均为大于等于0的整数,不保证数据没有前导零。

输入描述:

第一行输入一个n, 1 \le n \le 1000n,1≤n≤1000,代表测试数据的组数。
接下来n行,每行输入一个长度不超过10000的字符串。

输出描述:

对于每组输入,输出结果

输入

4
2+2
1+2
+12
0+0

输出

4
3
skipped
0

算法分析

高精度加法模拟,处理前导零

代码实现

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;
        int cnt=0,pos;
        int len=s.length();
        for(int i=0;i<s.length();i++)
        {
            if(s[i]=='+')
            {
                cnt++,pos=i;
            }
        }
        if(cnt!=1)
            cout<<"skipped"<<endl;
        else if(s[0]=='+'||s[len-1]=='+')
            cout<<"skipped"<<endl;
        else
        {
            int form=0,last=pos+1,qian=pos-1,hou=len-1;
            while(s[form]=='0')    form++;
            while(s[last]=='0')    last++;
            if(form>qian&&last>hou)
            {
                cout<<'0'<<endl;
            }
            else
            {
                string ans;
                int a=0,b=0,cnt=0,t=0;
                while(form<=qian||last<=hou)
                {
                    a=b=0;
                    if(form<=qian)    a=s[qian]-'0';
                    if(last<=hou)     b=s[hou]-'0';
                    ans[cnt++]=(a+b+t)%10+'0';
                    t=(a+b+t>9);
                    qian--,hou--;
                }
                if(t)
                    ans[cnt++]=t+'0';
                for(int i=cnt-1;i>=0;i--)
                     cout<<ans[i];
                cout<<endl;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值