字符串乘法

字符串乘法,一种巧妙的计算方法

string-multiply.js

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
const multiply = (num1, num2) => {
    const m = num1.length;
    const n = num2.length;
    const pos = new Array(m + n).fill(0);

    for (let i = m - 1; i >= 0; i--) {
        const n1 = +num1[i];
        for (let j = n - 1; j >= 0; j--) {
            const n2 = +num2[j];
            const multi = n1 * n2;
            const sum = pos[i + j + 1] + multi;

            pos[i + j + 1] = sum % 10;
            pos[i + j] += sum / 10 | 0;
        }
    }
    while (pos[0] === 0) {
        pos.shift();
    }
    return pos.length ? pos.join('') : '0';
};

const result = multiply('25','25');
console.log('result:'+result);

版权声明:著作权归作者所有。

thumb_up 0 | star_outline 0 | textsms 0