Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 347161 Accepted Submission(s): 67385
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
Author
Ignatius.L
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002
分析:高精度计算,大数相加!模版在博客中已给出,翻翻看,按照模版写就行了,要注意细节,空格的输出,因为这个PE了2次!
下面给出AC代码:
1 #include <bits/stdc++.h>
2 using namespace std;
3 int main()
4 {
5 char a1[1005],b1[1005];
6 int a[1005],b[1005],c[1005];//a,b,c分别存储加数,加数,结果
7 int x,i,j,n;
8 int lena,lenb,lenc;
9 while(scanf("%d",&n)!=EOF)
10 {
11 for(j=1;j<=n;j++)
12 {
13 memset(a,0,sizeof(a));//数组a清零
14 memset(b,0,sizeof(b));//数组b清零
15 memset(c,0,sizeof(c));//数组c清零
16 scanf("%s%s",&a1,&b1);
17 lena=strlen(a1);
18 lenb=strlen(b1);
19 for(i=0;i<=lena;i++)
20 a[lena-i]=a1[i]-'0';//将数串a1转化为数组a,并倒序存储
21 for(i=0;i<=lenb;i++)
22 b[lenb-i]=b1[i]-'0';//将数串b1转化为数组a,并倒序存储
23 x=0;//x是进位
24 lenc=1;//lenc表示第几位
25 while(lenc<=lena||lenc<=lenb)
26 {
27 c[lenc]=a[lenc]+b[lenc]+x;//第lenc位相加并加上次的进位
28 x=c[lenc]/10;//向高位进位
29 c[lenc]%=10;//存储第lenc位的值
30 lenc++;//位置下标变量
31 }
32 c[lenc]=x;
33 if(c[lenc]==0)//处理最高进位
34 lenc--;
35 printf("Case %d:\n",j);//格式要求吧!学着点
36 printf("%s + %s = ",a1,b1);//这也是格式要求吧!学着点
37 for(i=lenc;i>=1;i--)
38 printf("%d",c[i]);
39 printf("\n");
40 if(j!=n)//对于2组之间加空行的情况
41 printf("\n");
42 }
43 }
44 return 0;
45 }
java写法大数,真是有毒!
1 import java.math.BigInteger;
2 import java.util.Scanner;
3
4 public class Main {
5
6 /**
7 * @param args
8 */
9 public static void main(String[] args)
10 {
11 // TODO Auto-generated method stub
12 //System.out.println("Hello World!");
13 Scanner in=new Scanner(System.in);
14 while(in.hasNextInt())
15 {
16 // int []arr=new int[3];
17 int n;
18 n=in.nextInt();
19 for(int i=1;i<=n;i++)
20 {
21 BigInteger a,b;
22 a=in.nextBigInteger();
23 b=in.nextBigInteger();
24 if(i<n)
25 {
26 System.out.println("Case "+i+":");
27 System.out.print(a+" + "+b+" = ");
28 System.out.println(a.add(b));
29 System.out.println();
30 }
31 else
32 {
33 System.out.println("Case "+i+":");
34 System.out.print(a+" + "+b+" = ");
35 System.out.println(a.add(b));
36 }
37 }
38 }
39 }
40 }