meibin08 / free-programming-books

📚码农周报 免费的编程书籍,leetcode(力扣)题解、前端算法题,牛客网前端大厂面试题题解、提升工作效率的常用工具等📈🎉
https://susouth.com/
424 stars 60 forks source link

String-解题:2个正整数字符串 #26

Open meibin08 opened 5 years ago

meibin08 commented 5 years ago

阿里伯乐代码评测系统题(来自微信群,大佬的截图,自己汇总一下) 2个正整数字符串 AB的相加,返回结果, PS:考虑超长字符串相加

meibin08 commented 5 years ago

js解题思路:

var addToArrayForm = (A, B) => {

    let arrA = A.split("");
    let arrB = B.split("");
    if (A.length < B.length) {
        [arrA, arrB] = [arrB, arrA];
    }
    arrB.unshift(...(new Array(arrA.length - arrB.length).fill(0)));

    for (var i = arrA.length - 1; i >= 0; i--) {
        arrA[i] = parseInt(arrA[i]) + parseInt(arrB[i]);

        if (arrA[i] >= 10) {
            arrA[i] = arrA[i] % 10;

            if (i == 0) {
                arrA.unshift(1);
            } else {
                arrA[i - 1] = parseInt(arrA[i - 1]) + 1;
            }
        }
    };
    return arrA.join("");;

};

addToStringForm("19","1")

关注IT平头哥联盟