大数加法

来源:互联网 发布:51单片机红外线遥控 编辑:程序博客网 时间:2024/04/29 17:23
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
 

Sample Input
21 2112233445566778899 998877665544332211
 

Sample Output
Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110
题意非常简单。就是求大数的加法。这时候用正常的加法肯定是不行的,所以我们引入了大数加法这个概念。
通过string类或者字符数组来对这些数字进行储存,然后用模拟的思想将他模拟出来
#include<cstdio>#include<iostream>#include<string>using namespace std;string a,b;string jia(string a,string b){    while(a.size()<b.size())    {        a='0'+a;    }    while(a.size()>b.size())    {        b='0'+b;    }    a='0'+a;    b='0'+b;    for(int i=a.size()-1; i>=0; i--)    {        a[i]=a[i]+b[i]-'0';        if(a[i]>'9')        {            a[i]-=10;            a[i-1]++;        }    }    while(a.size()>1&&a[0]=='0')        a.erase(0,1);    return a;}int main(){    int t,T=0;    cin >> t;    while(t--)    {        T++;        cin >> a >> b;        string c=jia(a,b);        printf("Case %d:\n",T);        cout << a << " + " << b << " = " << c << endl;        if(t!=0)            cout << endl;    }    return 0;}


0 0