# A - A + B Problem II

xiaoxiao2021-02-28  4

## A - A + B Problem II

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

#include<stdio.h> #include<iostream> #include<algorithm> #include<stdlib.h> #include<string.h> using namespace std; char s1[10000],s2[10000]; int a[10000],b[10000],c[10000]; int main(){ int T,i,j; cin>>T; int cnt=1; for(int k=0;k<T;k++){ scanf("%s %s",s1,s2); memset(c,0,sizeof(c)); memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); int len1=strlen(s1); int len2=strlen(s2); for(i=0;i<len1;i++){ a[i]=s1[len1-i-1]-'0'; //把数字一个一个的倒着存储在数组中 } for(i=0;i<len2;i++){ b[i]=s2[len2-i-1]-'0'; } int max=len1>len2?len1:len2; for(i=0;i<=max;i++){ int sum=a[i]+b[i]+c[i]; if(sum>=10){//如果两个数字相加大于10，就证明要进位 c[i]=sum-10;//c数组存放进位后的数字 c[i+1]++;//进位后，c数组下一位的数据要加1 }else{ c[i]=sum;//如果不用进位的话，直接把相加后的结果存在c数组中，方便输出 } } printf("Case %d:\n",cnt); printf("%s + %s = ",s1,s2); if(c[max]==0){ max--; //前导0的判断 } for(i=max;i>=0;i--){ cout<<c[i]; } if(cnt!=T) cout<<endl<<endl; //考虑到每两组数据间多一行空格 else cout<<endl; cnt++; } return 0; }

Java代码

import java.util.Scanner; import java.math.BigInteger; public class Main { public static void main(String args[]){ int cnt=0; Scanner scan=new Scanner(System.in); int n=scan.nextInt(); while(n!=0){ n--; BigInteger a,b; a=scan.nextBigInteger(); b=scan.nextBigInteger(); System.out.println("Case "+(++cnt)+":"); System.out.println(a+" + "+b+" = "+a.add(b)); if(n!=0) System.out.println(); } } }