Problem A+B(Big Integer)大数相加

Problem A+B(Big Integer)

Time Limit:1000MS Memory Limit:65536KB

Description 
Give two positive integer A and B,calucate A+B.
Notice that A,B is no more than 500 digits.

Input 
The test case contain several lines.Each line contains two positive integer A and B.

Output 
For each input line,output a line contain A+B

Sample Input 
2 3
1231231231823192 123123123123123
1000000000000000 1

Sample Output 
5
1354354354946315
1000000000000001


此题是我们熟悉的大数相加,顾名思义大数肯定是超出int等基本类型范围的,因为必须采用字符串来模拟手工计算,是不是一夜回到小学的感觉,那就没啥了,直接上代码吧。有个注意点是如果两个数相加最高位产生进位,这个情况要注意下。比如:9+1=10,999+1=1000等。废话不多说了直接上代码:

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
    string a,b,sum;
    int diff,length;
    int carry = 0;
    while(cin >> a >> b)
    {
        if(a.length() < b.length())
        {
            b.insert(0,"0");
            diff = b.length() - a.length();
            a.insert(0,diff,'0');
            sum = b;
        }
        else if (a.length() > b.length())
        {
            a.insert(0,"0");
            diff = a.length() - b.length();
            b.insert(0,diff,'0');
            sum = a;
        }
        else//为了防止最高位进位,在前面多加一位
        {
            a.insert(0,"0");
            b.insert(0,"0");
            sum = b;
        }
        length = sum.length();
        for(int i = length-1; i >= 0; --i)
        {
            int temp_a = a[i] - '0';
            int temp_b = b[i] - '0';
            int s = temp_a + temp_b;
            if(s + carry > 9)
            {
                sum[i] = s + carry - 10 + '0';
                carry = 1;
            }
            else
            {
                sum[i] = s + carry + '0';
                carry = 0;
            }
        }
        if(sum[0] == '0')//把最高位的0去掉
        {
            sum.erase(0,1);
        }
        cout << sum << endl;
        sum.clear();
    }
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值