大数相乘,限制:不可用 BigInt

大数相乘,限制:不可用 BigInt

/**
* 大数相乘,限制:不可用 BigInt *
* 例如:
* 输入
* a = '11111111111111111111' * b = '22222222222222222222' * 返回
* '246913580246913580241975308641975308642' *
* @param {string} a * @param {string} b
* @return {string} */
const multiplied = (a, b) =>{
//这里写 javascript 代码实现
}
const multiplied = (a, b) => {
    if (a === '0' || b === '0') return '0'
    const m = a.length
    const n = b.length
    const res = Array(m + n).fill(0)
    for (let i = m - 1; i >= 0; i--) {
        for (let j = n - 1; j >= 0; j--) {
            const mul = (a[i] - '0') * (b[j] - '0')
            const p1 = i + j
            const p2 = i + j + 1
            const sum = mul + res[p2]
            res[p2] = sum % 10
            res[p1] += Math.floor(sum / 10)
        }
    }
    while (res[0] === 0) {
        res.shift()
    }
    return res.join('')
}
// 示例用法
const num1 = '1234567890'
const num2 = '9876543210'
const res = multiplied(num1, num2)
console.log(res) // 12193263111263526900

你可能感兴趣的:(JS,前端,javascript,开发语言)