無論你面試的是什麼崗位,應該都或多或少看到過這個問題 - 兩個長整數相加(兩數均爲正整數)要怎麼實現。如果a和b的位數不大,確實直接用類型轉換就可以求出a+b了,但是萬一a和b的位數都是幾百位呢,早就溢出了,這時候要怎麼計算呢?
這種情況下,有三種解決方法可供選擇:
一、 用字符串來存儲a和b的值;
二、 用數組來存儲a和b的值;
三、 用StringBuffer按位存儲;
四、 用鏈表來存儲a和b的值。
這四種方法都有一個共同點,就是無論哪一種方法,都可以不用擔心因爲數字太大而造成數值溢出出錯。其實原理差不多,即拆分成字符,然後遍歷兩個字符串。我們使用數組存儲的方式實現。
代碼實現:
package com.lzy;
import java.util.Scanner;
public class AddLongInteger {
public static void main(String[] args) {
//使用Scanner,獲取連續兩次輸入
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String addend = scanner.nextLine();
String aguend = scanner.nextLine();
System.out.println(AddTwoNums(addend,aguend));
}
}
/**
* 輸入參數:
* String addend:加數
* String augend:被加數
* 返回值:加法結果
*/
public static String AddTwoNums(String addend, String aguend){
//字符串拆分放進數組
char[] a1 = addend.toCharArray();
char[] a2 = aguend.toCharArray();
//結果數的長度是最長字符串長度+1,因爲可能存在進位的情況
int resultLength = a1.length>a2.length?a1.length+1:a2.length+1;
//初始化結果數組c
char[] r = new char[resultLength];
for(int i=0; i<resultLength; i++){
r[i]='0';
}
//翻轉a1,a2,便於從頭相加
char[] b1 = new char[a1.length];
char[] b2 = new char[a2.length];
for(int i=0; i<a1.length; i++){
b1[i] = a1[a1.length-1-i];
}
for(int i=0;i<a2.length; i++){
b2[i] = a2[a2.length-1-i];
}
//執行相加
for(int i=0; i<resultLength-1; i++){
int count = 0;
if(b1.length-1-i >=0 && b2.length-1-i>=0){
count = b1[i]-'0'+b2[i]-'0';//此處 -'0'和下邊+'0',是使用ASCII碼錶中數字相加減原理,免去類型轉換
}else if(b1.length-1-i >=0 && b2.length-1-i<0){
count = b1[i]-'0';
}else if(b1.length-1-i <0 && b2.length-1-i>=0){
count = b2[i]-'0';
}
int value = r[i] - '0' + count;
r[i] = (char)(value%10 + '0');
r[i+1] += value/10;
}
//判斷最後一位是否爲0
while(r[resultLength-1] == '0'){
resultLength --;
}
//將結果翻轉
char r2[] = new char[resultLength];
for(int i=0; i<resultLength; i++){
r2[resultLength-1-i] = r[i];
}
String result = new String(r2);
return result;
}
}
每天一道算法題,成就更好的自己!