大整數減法java版
package com.text1;
/*
* 大整數減法實現
*/
public class ReduceBignum {
public static void reduce(int a[],int b[]) {
int m = 0;
int n = 0;
int length = 0;
int []p = new int[a.length];
length = a.length;
m = b.length;
for (int i = 0; i <b.length; i++) {
if (a[i] >= b[i])
p[i] = a[i] - b[i];
else {
n = i;
//實現連環借位方法
while (true) {
if (a[i + 1] != 0) {
a[i + 1] = a[i + 1] - 1;
break;
}
else {
a[i + 1] = 9;
i = i + 1;
}
}
i = n;
p[i] = 10 - b[i] + a[i];
}
}
//解決a陣列多出來部分賦值問題,並第一次次排除頭為0的問題
for (int i = a.length-1; i >=b.length; i--) {
if (a[i] != 0) {
p[i] = a[i];
break;
}
else
length--;
}
for (int i = b.length; i < length-1; i++) {
p[i] = a[i];
}
//第二次徹底解決頭為0的問題出現低二次原因是第一次在解決頭出現問題僅僅解決的是a陣列賦值有0情況。
for (int i = length-1; i >= 0; i--) {
if (p[i] == 0)
length--;
else
break;
}
System.out.println("結果長度:"+length);
for (int i = 0; i < length ; i++)
System.out.print(p[i]+" ");;
p=null;
}
public static void main(String[] args) {
int[]a= {8,0,0,8,8,8,8};
int[]b= {9,9,0,8,8,8,7};
reduce(a,b);
}
}