Product sum difference of digits of a number in JavaScript


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

Updated on: 19-Apr-2021

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements