處理兩大數相乘,以下爲Java代碼:
- public class BigInt {
- /**
- * @param args
- */
- public static void main(String[] args) {
- String num1 = "1234" ;
- String num2 = "56789" ;
- mult(num1, num2) ;
- }
- /**
- * 直接輸出任意兩數相乘
- * @param n1
- * @param n2
- */
- public static void mult(String n1, String n2) {
- int[] result = new int[n1.length()+n2.length()] ; // 這裏爲存放兩數相乘後的得數。這個可以動態規劃
- // 字符串轉數字數組處理,算法的效率就是在這些地方浪費的
- int[] num1 = new int[n1.length()] ;
- int[] num2 = new int[n2.length()] ;
- for(int i = 0; i < n1.length(); i++) {
- num1[i] = Character.getNumericValue(n1.charAt(i)) ;
- }
- for(int i = 0; i < n2.length(); i++) {
- num2[i] = Character.getNumericValue(n2.charAt(i)) ;
- }
- // 核心代碼,其實簡單來說就是我們筆算怎麼算,代碼就怎麼算,這樣無論多大的數,都是可以算的
- // 裏面稍微做了些細緻的處理,認真看很容易就能明白
- int tempNum ;
- int tt ;
- for(int i = num1.length-1; i >= 0; i--) {
- for(int j = num2.length-1; j >= 0; j--) {
- tempNum = num1[i] * num2[j] ;
- tt = result.length - (num1.length-i) - (num2.length-j) ;
- if(tempNum >= 10) {
- f(result, tt, tempNum % 10) ;
- f(result, tt-1, tempNum / 10) ;
- }else {
- f(result, tt, tempNum) ;
- }
- }
- }
- // 輸出,這僅僅只是將數組前面的0去掉,去實際的答案
- boolean found = false ;
- for(int t : result) {
- if(t != 0 && found == false) {
- System.out.print(t) ;
- found = true ;
- }else if(found == true) {
- System.out.print(t) ;
- }
- }
- System.out.println() ;
- }
- /**
- * 相乘後相加處理,有關於兩數相加後>=10的時候應該怎麼進一位的處理,
- * 知道不在有進一位爲止
- * @param result
- * @param tTe
- * @param tempNum1
- */
- public static void f(int[] result, int tTe, int tempNum1) {
- int t ;
- while(true) {
- if(result[tTe+1] + tempNum1 >= 10) {
- t = result[tTe+1] ;
- result[tTe+1] = (result[tTe+1] + tempNum1) % 10 ;
- tTe-- ;
- tempNum1 = (t + tempNum1) / 10 ;
- }else {
- result[tTe+1] += tempNum1 ;
- break ;
- }
- }
- }
- }
雖說類庫裏面有大數處理類,但爲了提高算法水平,還是自己寫了下,希望對大家學習有幫助。