Leetcode problem 41 - 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 Example 2:
Input: n = 4421 Output: 21 Explanation: Product of digits = 4 _ 4 _ 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21
/**
* @param {number} n
* @return {number}
*/
var subtractProductAndSum = function (n) {
let nums = n.toString().split("");
let multipleNums = 1;
let sumNums = 0;
for (let i = 0; i < nums.length; i++) {
multipleNums *= nums[i];
sumNums += Number(nums[i]);
}
return multipleNums - sumNums;
};
let nums = n.toString().split('')
: Convert the integer n to a string, and then split the string into an array of individual digits. This array is stored in the variable nums
.
let multipleNums = 1;
and let sumNums = 0;
: Initialize two variables, multipleNums
to 1 (for multiplication) and sumNums
to 0 (for summation).
for (let i = 0; i < nums.length; i++) {
: Start a loop that iterates over each digit in the nums array.
multipleNums *= nums[i]
: For each digit, multiply the multipleNums
variable by the digit. This calculates the product of all the digits.
sumNums += Number(nums[i])
: For each digit, add the digit (converted back to a number) to the sumNums
variable. This calculates the sum of all the digits.
return multipleNums - sumNums;
: Calculate the difference between the product of the digits (multipleNums
) and the sum of the digits (sumNums
), and return the result.
Leave a comment