java实现大数减法算法

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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值