大整數求和演算法java版
阿新 • • 發佈:2018-12-04
package com.text1; import java.util.Scanner; /* * 大整數求和演算法 */ public class SubBignum{ public static void add(int[] a,int[] b) { int[] p; int m = 0; int n = 0; int flag = 0; //在初始分配結果p陣列長度多與最長長度儲存進位 if (a.length >= b.length) { p = new int[a.length + 1]; m = b.length; n = a.length + 1; } else { p = new int[b.length + 1]; m = a.length; n = b.length + 1; } //同有位置的加法 for (int i = 0; i < m; i++) { p[i] = (a[i] + b[i] + flag)%10; flag = (a[i] + b[i] + flag) / 10; } //多餘位置的加法 if (a.length >=b.length) { for (int i = m; i < a.length ; i++) { p[i] = (a[i] + flag) % 10; flag = (a[i] + flag) / 10; } if (flag != 0) { p[a.length] = flag; System.out.println( "結果長度:" + (a.length + 1) ); for (int i = 0; i < a.length + 1; i++) System.out.print(p[i] + " "); } else { System.out.println( "結果長度:" + a.length ); for (int i = 0; i < a.length; i++) System.out.print(p[i] + " "); } } if (b.length > a.length) { for (int i = m; i < b.length; i++) { p[i] = (b[i] + flag) % 10; flag = (b[i] + flag) / 10; } if (flag != 0) { p[b.length] = flag; System.out.println( "結果長度:" + (b.length + 1)); for (int i = 0; i < b.length + 1; i++) System.out.print( p[i] + " "); } else { System.out.println( "結果長度:" + b.length ); for (int i = 0; i < b.length ; i++) System.out.print(p[i] + " "); } } } public static void main() { int alength = 0; int blength = 0; int []a; int []b; Scanner scaner=new Scanner(System.in); System.out.print( "輸入長度alength:"); alength=scaner.nextInt(); a = new int[alength]; for (int i = 0; i < alength; i++) { a[i]=scaner.nextInt(); } System.out.print("輸入長度blength:"); blength=scaner.nextInt(); b = new int[blength]; for (int i = 0; i < blength; i++) { b[i]=scaner.nextInt(); } add(a, b); } }