A + B Problem II
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
分析:高精度计算,大数相加!模版在博客中已给出,翻翻看,按照模版写就行了,要注意细节,空格的输出,因为这个PE了2次!
下面给出AC代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
char a1[],b1[];
int a[],b[],c[];//a,b,c分别存储加数,加数,结果
int x,i,j,n;
int lena,lenb,lenc;
while(scanf("%d",&n)!=EOF)
{
for(j=;j<=n;j++)
{
memset(a,,sizeof(a));//数组a清零
memset(b,,sizeof(b));//数组b清零
memset(c,,sizeof(c));//数组c清零
scanf("%s%s",&a1,&b1);
lena=strlen(a1);
lenb=strlen(b1);
for(i=;i<=lena;i++)
a[lena-i]=a1[i]-'';//将数串a1转化为数组a,并倒序存储
for(i=;i<=lenb;i++)
b[lenb-i]=b1[i]-'';//将数串b1转化为数组a,并倒序存储
x=;//x是进位
lenc=;//lenc表示第几位
while(lenc<=lena||lenc<=lenb)
{
c[lenc]=a[lenc]+b[lenc]+x;//第lenc位相加并加上次的进位
x=c[lenc]/;//向高位进位
c[lenc]%=;//存储第lenc位的值
lenc++;//位置下标变量
}
c[lenc]=x;
if(c[lenc]==)//处理最高进位
lenc--;
printf("Case %d:\n",j);//格式要求吧!学着点
printf("%s + %s = ",a1,b1);//这也是格式要求吧!学着点
for(i=lenc;i>=;i--)
printf("%d",c[i]);
printf("\n");
if(j!=n)//对于2组之间加空行的情况
printf("\n");
}
}
return ;
}
java写法大数,真是有毒!
import java.math.BigInteger;
import java.util.Scanner; public class Main { /**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
//System.out.println("Hello World!");
Scanner in=new Scanner(System.in);
while(in.hasNextInt())
{
// int []arr=new int[3];
int n;
n=in.nextInt();
for(int i=1;i<=n;i++)
{
BigInteger a,b;
a=in.nextBigInteger();
b=in.nextBigInteger();
if(i<n)
{
System.out.println("Case "+i+":");
System.out.print(a+" + "+b+" = ");
System.out.println(a.add(b));
System.out.println();
}
else
{
System.out.println("Case "+i+":");
System.out.print(a+" + "+b+" = ");
System.out.println(a.add(b));
}
}
}
}
}