43.字符串相乘

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
/**
    * 计算形式
    *    num1
    *  x num2
    *  ------
    *  result
    */
var multiply = function (num1, num2) {
    if(num1 === '0' || num2 === '0') {
        return '0'
    }
    // 模拟乘法的过程,从个位数开始相乘
    // 需要用一个数组存,直接计算可能会超过int类型长度
    let sum = ''
    for (let i = num1.length - 1; i >= 0; i--) {
        let subSum = ''
        for (let j = num2.length - 1; j >= 0; j--) {
            let n1 = Number(num1[i])
            let n2 = Number(num2[j])
            let num = (n1 * n2).toString()
            if(num === '0') {
                continue
            }
            let needZero = (num1.length - 1 - i) + (num2.length - 1 - j)
            // 补0
            for (let k = 0; k < needZero; k++) {
                num += '0'
            }
            console.log(num)
            // 使用两个字符串的加法
            subSum = add(subSum, num)
        }
        sum = add(sum, subSum)
    }
    return sum
};

// 两个字符串相加, 因为字符串长度会很长,可能超过int类型长度
function add(str1, str2) {
    if (str1 === '') {
        return str2
    }
    if (str2 === '') {
        return str1
    }
    let prefix = 0 // 进1
    // 从个位数开始相加
    let i = str1.length - 1
    let j = str2.length - 1
    let res = ''
    while (i >= 0 || j >= 0 || prefix) {
        let n1 = Number(str1.charAt(i) || 0)
        let n2 = Number(str2.charAt(j) || 0)
        let result = n1 + n2 + prefix
        let num = result % 10
        prefix = result > 9 ? 1 : 0
        res = `${num}${res}`

        i--
        j--
    }
    return res
}

// console.log(multiply('18', '18'))
console.log(multiply("123456789", "987654321"))
// console.log(add('18', '19'))