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
本来以为这个题好简单的,只是输出格式有点特殊,然后,仔细一看,突然发现,貌似有点麻烦,虽然它是正整数的相加,但是,题目说,数字的长度不小于1000,事实证明,这么长的数字unsigned long long int 是不能解决的,所以说,要用字符串进行处理。代码如下(C++):
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
string sum(string&a,string&b)
{
string max,min;
int len1=a.length();
int len2=b.length();
if(len1<len2)
{
max=b;
min=a;
}
else
{
max=a;
min=b;
}
int maxlen=max.length();
int minlen=min.length();
int i,j;
for(i=maxlen-1,j=minlen-1; j>=0; j--,i--)
max[i]=max[i]+min[j]-'0';//加起来之后的数存到相应的max[i]中
for(i=maxlen-1; i>0; i--) //检测max中每一位的值,除了最前面的那一位
{
if(max[i]>'9')
{
max[i]=max[i]-10;
max[i-1]+=1;//进位
}
}
if(max[0]>'9')//检测第一位
{
max[0]=max[0]-10;//记得换掉max[0]的值
max="1"+max;//这里"1"或者'1'都可以
}
return max;
}
int main()
{
int n;
cin>>n;
int i=1;
while(n--)
{
string a,b;
cin>>a>>b;
cout<<"Case "<<i<<":"<<endl;
cout<<a<<" + "<<b<<" = "<<sum(a,b)<<endl;
if(n)
cout<<endl;
i++;
}
}
但是,用Java就不同了,因为Java中已经帮忙封装了相关的计算方法,只需要调用合适的包就OK了,如下:
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
int l=sc.nextInt();
for(int i=1;i<=l;i++){
if(i!=1) System.out.println();
BigInteger a,b;
a=sc.nextBigInteger();
b=sc.nextBigInteger();
System.out.println("Case "+i+":");
System.out.println(a+" + "+b+" = "+a.add(b));
}
}
}