大整数相加

2020-08-18  本文已影响0人  编程小王子AAA

大整数相加

/**
 * @data Administrator
 * @data 2020/8/15 0015
 */
public class BignumAdd {

    public static String bigNumberSum(String bignumberA, String bignumberB) {
        int maxLength = Math.max(bignumberA.length(), bignumberB.length());
        int[] arrayA = new int[maxLength + 1];
        for (int i = 0; i < bignumberA.length(); i++) {
            arrayA[i] = bignumberA.charAt(bignumberA.length() - 1 - i) - '0';
        }
        int[] arrayB = new int[maxLength + 1];
        for (int i = 0; i < bignumberB.length(); i++) {
            arrayB[i] = bignumberB.charAt(bignumberB.length() - 1 - i) - '0';
        }
        int[] res = new int[maxLength + 1];
        for (int i = 0; i < res.length; i++) {
            int temp = res[i];
            temp += arrayA[i];
            temp += arrayB[i];
            if (temp >= 10) {
                temp = temp - 10;
                res[i + 1] = 1;
            }
            res[i] = temp;
        }
        StringBuilder sb = new StringBuilder();
        boolean findFirst = false;
        for (int i = res.length - 1; i >= 0; i--) {
            if (!findFirst) {
                if (res[i] == 0) {
                    continue;
                }
                findFirst = true;
            }
            sb.append(res[i]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(bigNumberSum("100", "100"));
    }

}

上一篇下一篇

猜你喜欢

热点阅读