Skip to content

3754. Concatenate Non-Zero Digits and Multiply by Sum I

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 = 1 and sum = 1.
  • Therefore, the answer is x * sum = 1 * 1 = 1.

 

Constraints:

  • 0 <= n <= 109

Solutions

Solution 1: Simulation

We can simulate the required operation by processing the number digit by digit. While processing each digit, we concatenate non-zero digits to form a new integer \(x\) and calculate the digit sum \(s\). Finally, we return \(x \times s\).

The time complexity is \(O(\log n)\) and the space complexity is \(O(1)\).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def sumAndMultiply(self, n: int) -> int:
        p = 1
        x = s = 0
        while n:
            v = n % 10
            s += v
            if v:
                x += p * v
                p *= 10
            n //= 10
        return x * s
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public long sumAndMultiply(int n) {
        int p = 1;
        int x = 0, s = 0;
        for (; n > 0; n /= 10) {
            int v = n % 10;
            s += v;
            if (v != 0) {
                x += p * v;
                p *= 10;
            }
        }
        return 1L * x * s;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    long long sumAndMultiply(int n) {
        int p = 1;
        int x = 0, s = 0;
        for (; n > 0; n /= 10) {
            int v = n % 10;
            s += v;
            if (v != 0) {
                x += p * v;
                p *= 10;
            }
        }
        return 1LL * x * s;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func sumAndMultiply(n int) int64 {
    p := 1
    x := 0
    s := 0
    for n > 0 {
        v := n % 10
        s += v
        if v != 0 {
            x += p * v
            p *= 10
        }
        n /= 10
    }
    return int64(x) * int64(s)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function sumAndMultiply(n: number): number {
    let p = 1;
    let x = 0;
    let s = 0;

    while (n > 0) {
        const v = n % 10;
        s += v;
        if (v !== 0) {
            x += p * v;
            p *= 10;
        }
        n = Math.floor(n / 10);
    }

    return x * s;
}

Comments