大整数减法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);
        }

}
 

猜你喜欢

转载自blog.csdn.net/qq_41578371/article/details/82918362