Product sum difference of digits of a number in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number n. Our function should find the absolute difference between the sum and the product of all the digits of that number.

Example

Following is the code −

 Live Demo

const num = 434312;
const sumProductDifference = (num = 1) => {
    const sum = String(num)
        .split('')
        .reduce((acc, val) => acc + +val, 0);
 
    const product = String(num)
        .split('')
        .reduce((acc, val) => acc * +val, 1);
 
    const diff = product - sum;
 
    return Math.abs(diff);
};
console.log(sumProductDifference(num));

Output

271
raja
Published on 19-Apr-2021 14:15:26
Advertisements