大数相加 C++版+java版
A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 468200 Accepted Submission(s): 90552
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
要注意格式啊,每两组测试用例之间有一空行,也就是说最后一组例子没空行。
自己写的:
很容易理解,模拟两个数相加
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define range 1005
int m=1;
void add(char a[],char b[],char c[])
{
int i,j,k=0,current,carry=0,len;
len=strlen(a)>strlen(b)?strlen(a):strlen(b);
len+=3;
char res[range];
char x,y;
i=strlen(a)-1;
j=strlen(b)-1;
while(i>=0||j>=0)
{
if(i<0)
x='0';
else
x=a[i];
if(j<0)
y='0';
else
y=b[j];
current=x-'0'+y-'0';
if(carry)
current+=1;
if(current>9)
{
current%=10;
carry=1;
}
else carry=0; //这忘了一次,哇了两次
res[k++]=current+'0';
i--;
j--;
}
if(carry)
res[k++]='1';
res[k]='\0';
for(i=k-1,j=0;i>=0;i--,j++)
c[j]=res[i];
c[j]='\0';
return ;
}
int main()
{
char a[range],b[range],c[range];
int n;
cin>>n;
while(n--)
{
cin>>a>>b;
add(a,b,c);
cout<<"Case "<<m<<":"<<endl;
cout<<a<<" + "<<b<<" = "<<c<<endl;
if(n!=0)
cout<<endl;
m++;
}
return 0;
}
java版的:
开挂吧
package 大数;
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int m=1;
while(n>0)
{
BigDecimal a=in.nextBigDecimal();
BigDecimal b=in.nextBigDecimal();
System.out.println("Case "+m+":");
System.out.println(a+" + "+b+" = "+a.add(b));
if(n!=1)
System.out.println();
n--;
m++;
}
}
}