【每日一题(19)】A + B Problem II(大数相加) HDU

来源:互联网 发布:nga npc数据库 编辑:程序博客网 时间:2024/06/06 02:11

A + B Problem II(大数相加) HDU - 1002

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

2
1 2
112233445566778899 998877665544332211

Sample Output

Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

题意

题目就是要模拟大数相加,所以我们把人类算数字相加模拟一下就行了;
这道题格式错误了7次,尴尬,一直找不出输出格式啥意思,看了几遍才懂T_T

题解

#include<iostream>#include<cstring>#include<cstdio>using namespace std;int main(void){  int n;  scanf("%d\n",&n);  int t = 0;  while(n--){    char a[10005] = {0},b[10005] = {0},a1[10005] = {0},b1[10005] = {0},c[10005] = {0};    scanf("%s %s",a,b);    int lena = strlen(a);    int lenb = strlen(b);    for(int i = 0;i < lena; i++)      a1[lena - i - 1] = a[i];    a1[lena] = 0;    for(int i = 0;i < lenb; i++)      b1[lenb - i - 1] = b[i];    b1[lenb] = 0;    int maxlen = lena > lenb? lena : lenb;    for(int i = lena;i < maxlen; i++)      a1[i] = '0';    a1[maxlen] = 0;    for(int i = lenb;i < maxlen; i++)      b1[i] = '0';    b1[maxlen] = 0;    int fit = 0;    for(int i = 0;i < maxlen; i++){      c[i] = a1[i] - '0' + b1[i] - '0' + fit;      if(c[i] > 9){        fit = 1;        c[i] = c[i] - 10 + '0';      }      else{        fit = 0;        c[i] += '0';      }    }    if(fit == 1){      c[maxlen] = '1';      maxlen += 1;    }    t++;    cout<<"Case "<<t<<":"<<endl;    cout<< a <<" + "<<b<<" = ";    for(int i = maxlen - 1;i >= 0; i--){      cout << c[i];    }    cout << endl;    if(n != 0)      cout << endl;  }  return 0;}
原创粉丝点击