Concatenate Non-Zero Digits and Multiply by Sum I Problem
Description
LeetCode Problem 3754.
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 = 1 and sum = 1.
- Therefore, the answer is x * sum = 1 * 1 = 1.
Constraints:
0 <= n <= 10^9
Solution
Approach: Simulation
Process the digits of n from the last one to the first. Keep x, the number built from the non-zero digits so far, a place value p that starts at 1, and the digit sum s. For each non-zero digit v, add v to s, add p * v to x, and multiply p by 10. Zeros are skipped, so they never take up a place. Going from the right means each new digit lands in the next higher position, which keeps the original order.
At the end return x * s. The product can reach about 8 * 1010, so use a 64-bit integer in languages with fixed-size ints.
Complexity: O(log n) time and O(1) space.
class Solution:
def sumAndMultiply(self, n: int) -> int:
p = 1
x = s = 0
while n:
n, v = divmod(n, 10)
if v:
s += v
x += p * v
p *= 10
return x * s