HDOJ 1002:大数加法

6 篇文章 0 订阅
思路:字符串模拟加法,设置carry进位,右对齐字符串,从右向左相加,从左到右输出结果。
#include <iostream>
using namespace std;

int main()
{
    const int N =1005;
    string a, b, aa,bb;
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>a>>b;
        aa = a;
        bb = b;
        if(a.length()<b.length())
            a.insert(0,b.length()-a.length(),'0');
        else
            b.insert(0,a.length()-b.length(),'0');
         b.insert(0,1,'0');
         a.insert(0,1,'0');
        int carry = 0;
        char c[N]={0};
        for(int j=a.length()-1; j>=0; j--)
        {
            c[j] = carry + a[j] + b[j] - '0' - '0';
            carry = c[j]/10;
            c[j] %= 10;
        }
        int m=0;
        while(c[m]=='\0')
            m++;
        cout<<"Case "<<i+1<<":\n"<<aa<<" + "<<bb<<" = ";
        for(;m<a.length();m++)
            cout<<char(c[m]+'0');
        cout<<endl;
        if(i!=n-1)
            cout<<endl;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值