-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubtractProductAndSum.js
More file actions
39 lines (32 loc) · 844 Bytes
/
subtractProductAndSum.js
File metadata and controls
39 lines (32 loc) · 844 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Problem: 1281. Subtract the Product and Sum of Digits of an Integer
* Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example 1:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
*/
/**
* @param {number} n
* @return {number}
*/
var subtractProductAndSum = function (n) {
const arr = findDigits(n);
console.log("arr: ", arr);
const prod = arr.reduce((acc, num) => acc * num);
const sum = arr.reduce((acc, num) => acc + num);
return prod - sum;
};
function findDigits(number) {
let arr = [];
while (number > 0) {
let digit = number % 10;
number = Math.floor(number / 10);
arr.push(digit);
}
return arr.reverse();
}
console.log(subtractProductAndSum(643));