<span style="font-size:18px;">/*
*
* 輸入兩個整數a和b,輸出這兩個整數的和。a和b都不超過100位。
*/
import java.util.Scanner;
public class Main {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
String str1 = sc.next(); //存儲加數
String str2 = sc.next(); //存儲被加數
int r = 0; //保存進位
int n = 0; //結果數組的長度
//因爲在運算過程中可能存在進位,故此把n設置成比這兩個數中位數大的還要大1
if (str1.length() > str2.length())
n = str1.length() + 1;
else
n = str2.length() + 1;
char[] a = str1.toCharArray();
char[] b = str2.toCharArray();
int[] a1 = new int[n];
int[] b1 = new int[n];
int[] c = new int[n];
//把字符數組轉換成int型的,並且按個十百千萬.....這樣的順序存儲
for (int i = 0; i < str1.length(); i++) {
a1[i] = (int) a[str1.length() - i - 1] - 48;
}
for (int i = 0; i < str2.length(); i++) {
b1[i] = (int) b[str2.length() - i - 1] - 48;
}
//計算,並將結果保存到c數組中
for (int i = 0; i < n; i++) {
int t = a1[i] + b1[i] + r;
r = t / 10;
c[i] = t % 10;
}
//檢測最高位是否爲0,如果是0,則不輸出最高位,否則,從後向前遍歷整個數組
if (c[n-1] == 0) {
for (int i = n - 2; i >= 0; i--) {
System.out.print(c[i]);
}
} else {
for (int i = n-1 ; i >= 0; i--) {
System.out.print(c[i]);
}
}
}
}
</span>
//由於本人能力有限,所寫程序不夠完美,望各位大神指點一二,小弟不勝感激。高精度加法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.