您的位置:首页 > 编程语言 > Java开发

java实现大数减法算法

2017-10-26 18:49 316 查看
public static char[] subTract(int[] a,int[] b){
int cLength = b.length;
char sign = '+';
// 长度大,肯定正数
if(a.length > b.length){
cLength = a.length;
sign = '+';
} else if(a.length == b.length) {//长度等于,要逐位比较
int i = 0;
// 找出哪一位值不同
while(i<cLength && a[i] == b[i]){
i++;
}
// 如果全都相同,直接返回值为一个0的数组
if(i == cLength){
return new char[]{'0'};
}
cLength = cLength - i;
if(a[i] > b[i]){
sign = '+';
} else {
sign = '-';
}
} else {// 长度小于,肯定负数
sign = '-';
cLength = b.length;
}
if(sign == '+'){
int[] c = subWhenAbig(a,b,cLength);
char[] result = new char[c.length];
for(int i=0;i<c.length;i++){
result[i] = String.valueOf(c[i]).toCharArray()[0];
}
return result;
} else {
int[] c = subWhenAbig(b,a,cLength);
char[] result = new char[c.length + 1];
result[0] = '-';
for(int i=0;i<c.length;i++){
result[i+1] = String.valueOf(c[i]).toCharArray()[0];
}
return result;
}
}

private static int[] subWhenAbig(int[] a, int[] b, int cLength) {
int[] c = new int[cLength];

int i = a.length -1;
int j = b.length -1;
int k = c.length -1;
while(i >= 0){
if(a[i] < 0){
a[i] = 10 + a[i];
a[i-1] = a[i-1] - 1;
}
if(j < 0){
c[k] = a[i];
} else {
if(a[i] >= b[j]){
c[k] = a[i] - b[j];
} else {
c[k] = a[i] - b[j] + 10;
a[i-1] = a[i-1] - 1;
}
}
i--;j--;k--;
}
boolean firstZero = true;
for(int x = 0;x < c.length;x++){
if(c[x] == 0 && firstZero){
cLength--;
} else {
firstZero = false;
}
}
int[] result = new int[cLength];
int y = 0;
for(int x = c.length - cLength;x < c.length;x++,y++){
result[y] = c[x];
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: