2022/12/20

LeetCode 1281. Subtract the Product and Sum of Digits of an Integer

問題:減去整數的乘積和數字和
解法:先將nums轉為array,透過reduce計算後將結果輸出即可 JavaScript
/**
 * @param {number} n
 * @return {number}
 */
var subtractProductAndSum = function (n) {
    const nums = n.toString().split("");
    const product = nums.reduce((s, n) => s * parseInt(n), 1);
    const sum = nums.reduce((s, n) => s + parseInt(n), 0);

    return product - sum;
};