DDSA Solutions

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

Time: O(log n)
Space: O(1)

Problem Overview

Strip zeros from n while preserving order of the remaining digits to form x.

Intuition

Strip zeros from n while preserving order of the remaining digits to form x. The sum is the digit sum of x (zeros in the original number contribute nothing). A single right-to-left pass can build x with a place-value multiplier and accumulate sum at the same time.

Algorithm

  1. 1Initialize x = 0, sum = 0, place = 1.
  2. 2While n > 0: read digit = n % 10.
  3. 3If digit != 0: add digit to sum, add digit * place to x, multiply place by 10.
  4. 4Divide n by 10 and continue.
  5. 5Return x * sum (use long to avoid overflow on large products).

Example Walkthrough

Input: n = 10203004

  1. 1.Non-zero digits in order: 1, 2, 3, 4 → x = 1234.
  2. 2.sum = 1 + 2 + 3 + 4 = 10.
  3. 3.Answer = 1234 * 10 = 12340.

Output: 12340

Common Pitfalls

  • Build x from right to left with place *= 10 so digit order matches the original number.
  • sum is over digits in x only; skipping zeros in n is equivalent to ignoring zero addends.
  • Edge case n = 0 or all-zero digits: x = 0 and sum = 0, return 0.
3754.cs
C#
// Approach: Scan digits right-to-left; append non-zero digits to x and add them to sum.
// Return x * sum. Processing from the right keeps original digit order in x.
// Time: O(log n) Space: O(1)
public class Solution
{
    public long SumAndMultiply(int n)
    {
        long x = 0;
        long sum = 0;
        long place = 1;

        // Process digits from right to left
        while (n > 0)
        {
            long digit = n % 10;
            if (digit != 0)
            {
                sum += digit;
                x += digit * place;
                place *= 10;
            }
            n /= 10;
        }

        return x * sum;
    }
}
Was this solution helpful?

Related Problems