Description
You are given an integer n.
Form a new integer x by concatenating all the non-zero digits of n in their original order. If there are no non-zero digits, x = 0.
Let sum be the sum of digits in x.
Return an integer representing the value of x * sum.
Example 1:
Input: n = 10203004
Output: 12340
Explanation:
- The non-zero digits are 1, 2, 3, and 4. Thus,
x = 1234. - The sum of digits is
sum = 1 + 2 + 3 + 4 = 10. - Therefore, the answer is
x * sum = 1234 * 10 = 12340.
Example 2:
Input: n = 1000
Output: 1
Explanation:
- The non-zero digit is 1, so
x = 1andsum = 1. - Therefore, the answer is
x * sum = 1 * 1 = 1.
Constraints:
0 <= n <= 109
Solutions
Could have potentially improved by keeping a pow10 variable (with *= 10 on every iteration) and avoiding the Math.pow call.
Language: javascript(2026-07-07 06:49)DONE
CPU Performance100.00%
Memory Performance67.86%
/**
* @param {number} n
* @return {number}
*/
var sumAndMultiply = function(n) {
let x = 0;
let sum = 0;
let count = 0;
while (n > 0) {
const rem = n % 10;
if (rem > 0) {
x += rem * Math.pow(10, count);
sum += rem;
count++;
}
n = Math.floor(n / 10);
}
return x * sum;
};