1002-A + B Problem II

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
2 1 2 112233445566778899 998877665544332211
 
Sample Output
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
 
解题思路:用数组模拟一个很大的数,一位一位地加,注意进位就行啦
 
AC代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
char x[10000],y[10000];
int a[10000],b[10000],c[10000];
int main() {
 int T;
 scanf("%d",&T);
 for(int k=1;k<=T;++k) {
  scanf("%s%s",x,y);
  int l1=strlen(x);
  int l2=strlen(y);
  memset(a,0,sizeof(a));
  memset(b,0,sizeof(b));
  memset(c,0,sizeof(c));
  int j=0;
  for(int i=l1-1;i>=0;--i)
  a[j++]=(int )x[i]-48;
  j=0;
  for(int i=l2-1;i>=0;--i)
  b[j++]=(int )y[i]-48;
  int l=l1>l2? l1:l2;
  for(int i=0;i<l;++i) {
   c[i]=c[i]+a[i]+b[i];
   c[i+1]+=c[i]/10;
   c[i]%=10;
  }
  if(c[l+1]!=0)
  l++;
  printf("Case %d:\n",k);
  printf("%s + %s = ",x,y);
  for(int i=l-1;i>=0;--i)
  printf("%d",c[i]);
  printf("\n");
  if(k!=T)
  printf("\n");
 }
  return 0;
}
 
posted @ 2013-03-31 23:24  xiaxiaosheng  阅读(104)  评论(0)    收藏  举报