Javascript solution


  • 0
    L

    we can calculate one to one;

    /**
     * @param {string} num1
     * @param {string} num2
     * @return {string}
     */
    var addStrings = function(num1, num2) {
        if(num1.length > num2.length)
            return add(num1, num2);
        else
            return add(num2, num1);
    };
    
    function add(str1, str2){
        const len1 = str1.length;
        const len2 = str2.length;
        let carry = 0;
        const arr = [];
        for(let i = 1; i <= len1; i++){
            let sum = 0;
            if(i > len2)
                sum = parseInt(str1[len1 - i]) + carry;
            else
                sum = parseInt(str1[len1 - i]) + parseInt(str2[len2 - i]) + carry;
            if(sum >= 10){
                sum -= 10;
                carry = 1;
            }else
                carry = 0;
            arr.push(sum);
        }
        if(carry)
            arr.push(carry);
        return arr.reverse().join('');
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.