HDU1002大整數相加,因爲題目告訴你了這些整數你不能用32位整數來表示出來,所以必須將它們轉換爲其他類型來處理。這裏介紹兩種JAVA解決的方法,第一種是利用JAVA類庫提供的大整數類解決,另外一種是利用自定義類的方法解決。這裏主要介紹自定義類的方法,因爲Java類庫提供的方法沒什麼好說的,只要學會用就行。而自定義類的方法可以修改成c/c++來解決,核心算法差不多。不多說,先上題:
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
使用Java類庫解決代碼:
package ACM;
import java.util.Scanner;
import java.math.BigInteger;
public class BigIntegerTest {
public static void main(String []args) {
Scanner in=new Scanner(System.in);
int t=in.nextInt();
for(int i=1;i<=t;i++) {
BigInteger a,b,c;
a=in.nextBigInteger();
b=in.nextBigInteger();
c=a.add(b);
System.out.println("Case " + i + ":");
System.out.println(a + " + " + b + " = " + c);
if(i!=t)
System.out.println();
}
in.close();
}
}
使用自定義類解決代碼:
package ACM;
//HDU1002
import java.util.Scanner;
public class IntegerAddOne {
public String Add(String str1,String str2) {
String str="";
int len1=str1.length();
int len2=str2.length();
if(len1<len2) {//如果長度不一樣則對位
for(int i=0;i<len2-len1;i++)
str1="0"+str1;
}
else {
for(int i=0;i<len1-len2;i++)
str2="0"+str2;
}
int cf=0;
int temp;
for(int i=str1.length()-1;i>=0;i--) {
temp=str1.charAt(i)-'0'+str2.charAt(i)-'0'+cf;//計算第i位的值
cf=temp/10;//第i位的進位
temp%=10;//結果的第i位
str=(char) (temp+'0')+str;
}
if(cf!=0) {
str=(char) (cf+'0')+str;//最高位補1
}
return str;
}
public static void main(String []args) {
Scanner in=new Scanner(System.in);
int t=in.nextInt();
in.nextLine();
for(int i=1;i<=t;i++) {
String str=in.nextLine();
String Str[]=str.split(" ");
String str1=Str[0];
String str2=Str[1];
IntegerAddOne demo=new IntegerAddOne(); //通過類去調用
System.out.println("Case " + i + ":");
System.out.println(str1 + " + " + str2 + " = " + demo.Add(str1, str2));
if(i!=t)
System.out.println();
}
in.close();
}
}
str1和str2分別用來保存兩個大整數對應的字符串,從右往左依次保存個位數,十位數,百位數…首先判斷兩個字符串的長度是否一致,若不一致,則需要在高位補零。然後從個位數開始,由於每次相加拿出來的都是字符,所以要逐位減去‘0’相加再加上進位值cf,cf的初始值爲0,如果相加大於等於10則進位,用cf來保存進位值。等到所有的位都相加完了還要判斷進位值是否爲1,若爲1即最後一次相加的結果還沒進位,就要在最前面補1。最後結果就出來了。
這道題有些細節問題,它每個實例之間要用空行來隔開,所以在最後一個實例之前都要輸出一行空行,最後一個實例則不需要。