美文网首页
大整数相加

大整数相加

作者: 编程小王子AAA | 来源:发表于2020-08-18 09:51 被阅读0次

    大整数相加

    /**
     * @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"));
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:大整数相加

          本文链接:https://www.haomeiwen.com/subject/qaczdktx.html