大数加法(Java实现)

输入为两个String类型的大数,求这两个数之和

代码如下(原理代码注释中有说明):

public class BigNumAdd {

    public String add(String num1,String num2){
        //将两个数转化为数组
        char[] chars1 = num1.toCharArray();
        char[] chars2 = num2.toCharArray();

        //用来存放结果,结果的长度一定是等于最大那个数的长度或者其长度加1
        int[] res = new int[Math.max(chars1.length,chars2.length)+1];
        int count = 0;
        int idx1=chars1.length-1,idx2=chars2.length-1;
        //对应位置上相加,如果一个数长度大于另一个,在计算时,超过短的那个数的长度时,令其为0
        //例如,123+26,对应就是3+6,2+2,1+0;
        for(int i=res.length-1;i>=0;i--){
            int a = (count>=chars1.length)?0:(chars1[idx1--]-'0');
            int b = (count>=chars2.length)?0:(chars2[idx2--]-'0');
            count++;
            res[i] = a+b;
        }
        
        //进行进位计算
        for(int i=res.length-1;i>0;i--){
            res[i-1] += res[i]/10;
            res[i] = res[i]%10;
        }
        res[0] += res[1]/10;

        String result = "";
        //判断第一位是否为0,将数组中的数拼接起来
        if(res[0]==0) {
            for (int i = 1; i < res.length; i++) {
                result += res[i];
            }
        }else {
            for (int i = 0; i < res.length; i++) {
                result += res[i];
            }
        }
        return result;
    }

    //测试
    public static void main(String[] args) {
        BigNumAdd bigNumAdd = new BigNumAdd();
        String res1 = bigNumAdd.add("4239482309480329840923840932490234334","324837483749827948723942");
        BigInteger bigInteger = new BigInteger("4239482309480329840923840932490234334");
        BigInteger bigInteger1 = new BigInteger("324837483749827948723942");
        System.out.println(res1);
        System.out.println(bigInteger.add(bigInteger1));
        System.out.println(res1.equals( (bigInteger.add(bigInteger1)).toString()));
    }
}

测试结果如下:

你可能感兴趣的:(算法题,Java)