Description
You are given a positive integer n. Determine whether n is divisible by the sum of the following two values:
-
The digit sum of
n(the sum of its digits). -
The digit product of
n(the product of its digits).
Return true if n is divisible by this sum; otherwise, return false.
Example 1:
Input: n = 99
Output: true
Explanation:
Since 99 is divisible by the sum (9 + 9 = 18) plus product (9 * 9 = 81) of its digits (total 99), the output is true.
Example 2:
Input: n = 23
Output: false
Explanation:
Since 23 is not divisible by the sum (2 + 3 = 5) plus product (2 * 3 = 6) of its digits (total 11), the output is false.
Constraints:
1 <= n <= 106
Solutions
This function checks whether a number n is divisible by the sum of its digits plus the product of its digits. It starts with a copy of n in x, a running sum of 0, and a running mult of 1. Inside the while loop it repeatedly peels off the last digit with x % 10, adds that digit to sum, multiplies it into mult, and then drops the digit from x using Math.floor(x / 10), stopping once x reaches 0. For example, with n = 99 the digits are 9 and 9, giving a sum of 18 and a product of 81. Finally it returns true if n % (sum + mult) === 0, meaning n divides evenly by that combined value, and false otherwise.
/**
* @param {number} n
* @return {boolean}
*/
var checkDivisibility = function(n) {
let x = n;
let sum = 0;
let mult = 1;
while (x !== 0) {
const rem = x % 10;
sum += rem;
mult *= rem;
x = Math.floor(x / 10);
}
return n % (sum + mult) === 0;
};