#3754

Concatenate Non-Zero Digits and Multiply by Sum I

Easy
MathString ManipulationDigit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

Directly process the digits of n while calculating x and sum in one pass to improve efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize x as 0 and sum as 0.
  2. 2Step 2: For each digit in n, if it's non-zero, update x and add to sum.
  3. 3Step 3: Return x * sum.
solution.py11 lines
1def concatenate_and_multiply(n):
2    x, sum_digits = 0, 0
3    factor = 1
4    while n > 0:
5        digit = n % 10
6        if digit != 0:
7            x = digit * factor + x
8            sum_digits += digit
9            factor *= 10
10        n //= 10
11    return x * sum_digits

Complexity note: This is O(n) because we process each digit once, but we use constant space for variables.

  • 1Non-zero digits are crucial for forming x.
  • 2The sum of digits directly influences the final result.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.