Facebook Pixel

3726. Remove Zeros in Decimal Representation

EasyMathSimulation
LeetCode ↗

Problem Description

You are given a positive integer n.

Your task is to remove all zeros from the decimal representation of n, and return the resulting integer.

In other words, look at n digit by digit, discard every digit that is 0, and keep the remaining digits in their original order. The number formed by these remaining digits is the answer.

For example:

  • If n = 1020030, removing all zeros gives 123.
  • If n = 105, removing all zeros gives 15.
  • If n = 999, there are no zeros to remove, so the answer is 999.

Since n is a positive integer, it always contains at least one nonzero digit, so the result is guaranteed to be a valid positive integer.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

How We Pick the Algorithm

Why Simulation / Basic DSA?

This problem maps to Simulation / Basic DSA through a short path in the full flowchart.

Tree orgraph?noSimulation/ directcalculation?yesSimulation /Basic DSA

Extracting digits, filtering out zeros, and rebuilding the number is a straightforward arithmetic simulation.

Open in Flowchart

Intuition

The most natural way to "remove zeros" might be to convert n to a string, filter out the '0' characters, and convert it back to an integer. That works, but it raises a question: can we do this purely with arithmetic, without string conversion?

The key observation is that we can take apart a number digit by digit using math:

  • n % 10 gives us the last digit of n.
  • n // 10 chops off that last digit, letting us move on to the next one.

By repeating these two operations, we visit every digit of n from the lowest position to the highest.

Now, while extracting digits, we simply skip any digit that is 0 and keep the nonzero ones. The remaining challenge is rebuilding the answer correctly.

Since we are processing digits from right to left, each nonzero digit we keep should land in the next available position of the result — first the ones place, then the tens place, then the hundreds place, and so on. We can track this with a place-value multiplier k that starts at 1:

  • When we find a nonzero digit x, it belongs at position k, so we add k * x to the answer.
  • Then we advance the position by setting k *= 10.

Crucially, k only grows when we keep a digit. When we skip a zero, k stays the same — which is exactly what makes the zeros disappear: the digits to the left of a zero shift down to fill its place automatically.

Once n has been fully consumed, the accumulated answer is n with all zeros removed, built entirely with arithmetic in a single pass over the digits.

Pattern Learn more about Math patterns.

Solution Approach

k = 1 # place value for the next kept digit (1, 10, 100, ...) ans = 0 # the result being built


- `k` tracks where the next nonzero digit should go in the answer.
- `ans` accumulates the final number.

**2. Loop until all digits of `n` are consumed**

```python
while n:
    x = n % 10

n % 10 extracts the current lowest digit x.

3. Keep the digit only if it is nonzero

    if x:
        ans = k * x + ans
        k *= 10
  • k * x places digit x at the correct position (ones, tens, hundreds, ...).
  • Adding it to ans inserts the digit without disturbing the digits already placed below it.
  • k *= 10 advances the place value — but only when a digit is kept. If x is 0, we do nothing, so the next nonzero digit naturally slides down into the position the zero would have occupied. This is precisely what deletes the zeros.

4. Move to the next digit

    n //= 10

Integer division by 10 discards the digit we just processed.

5. Return the result

return ans

Example Walkthrough

Let's trace the algorithm with n = 1020030. The expected answer is 123.

We start with k = 1 and ans = 0, then peel off digits from the right using n % 10 and n //= 10:

Stepn (before)digit x = n % 10Actionansk
110200300skip (zero)01
21020033keep: ans = 1·3 + 0 = 3310
3102000skip (zero)310
410200skip (zero)310
51022keep: ans = 10·2 + 3 = 2323100
6100skip (zero)23100
711keep: ans = 100·1 + 23 = 1231231000

After step 7, n becomes 0, the loop ends, and we return ans = 123.

Two details worth noticing in the trace:

  1. Zeros never advance k. In steps 1, 3, 4, and 6 the digit is 0, so both ans and k stay frozen. That's why the digit 2 (originally in the thousands place of 1020030) lands in the tens place of the answer — every kept digit slides down to fill the gaps the zeros left behind.

  2. Building from the right keeps order intact. Each kept digit is attached at place value k, which is always larger than everything already in ans. So even though we process digits in reverse (3 → 2 → 1), they end up in their original left-to-right order: 1, 2, 3123.

Solution Implementation

1class Solution:
2    def removeZeros(self, n: int) -> int:
3        # place_value tracks the positional weight (1, 10, 100, ...)
4        # for the next non-zero digit in the result
5        place_value = 1
6        result = 0
7
8        # Process digits of n from least significant to most significant
9        while n:
10            digit = n % 10  # Extract the last digit
11            if digit:
12                # Keep non-zero digits: prepend the digit to the result
13                # at its current place value
14                result = place_value * digit + result
15                place_value *= 10  # Shift place value for the next kept digit
16            # Zero digits are simply skipped (not added to result)
17            n //= 10  # Remove the last digit from n
18
19        return result
20
1class Solution {
2    public long removeZeros(long n) {
3        // 'placeValue' represents the positional weight (1, 10, 100, ...) 
4        // for the next non-zero digit in the result
5        long placeValue = 1;
6        // 'result' accumulates the final number with all zero digits removed
7        long result = 0;
8
9        // Process the number digit by digit, from the least significant digit
10        while (n > 0) {
11            // Extract the last digit of n
12            long digit = n % 10;
13
14            // Only keep the digit if it is non-zero
15            if (digit > 0) {
16                // Place the digit at the current position in the result
17                result = placeValue * digit + result;
18                // Move to the next higher position for the next non-zero digit
19                placeValue *= 10;
20            }
21
22            // Remove the last digit from n
23            n /= 10;
24        }
25
26        return result;
27    }
28}
29
1class Solution {
2public:
3    long long removeZeros(long long n) {
4        // 'placeValue' represents the current decimal place (1, 10, 100, ...)
5        // used to build the result number from its least significant digit.
6        long long placeValue = 1;
7        // 'result' accumulates the final number with all zero digits removed.
8        long long result = 0;
9
10        // Process the number digit by digit, from least significant to most significant.
11        while (n > 0) {
12            // Extract the last digit of n.
13            long long digit = n % 10;
14
15            // Only keep non-zero digits.
16            if (digit > 0) {
17                // Place the digit at the current place value and add it to the result.
18                result = placeValue * digit + result;
19                // Move to the next higher decimal place.
20                placeValue *= 10;
21            }
22
23            // Remove the last digit from n.
24            n /= 10;
25        }
26
27        return result;
28    }
29};
30
1/**
2 * Removes all zero digits from a given number.
3 *
4 * The algorithm processes the number digit by digit from right to left.
5 * Non-zero digits are accumulated into the result, while zero digits are skipped.
6 *
7 * @param n - The input number whose zero digits should be removed
8 * @returns The resulting number after removing all zeros
9 */
10function removeZeros(n: number): number {
11    // Place value multiplier for building the result (1, 10, 100, ...)
12    let placeValue: number = 1;
13    // Accumulator for the final result
14    let result: number = 0;
15
16    // Process each digit of n from least significant to most significant
17    while (n) {
18        // Extract the last digit
19        const digit: number = n % 10;
20
21        // Only keep non-zero digits
22        if (digit) {
23            // Prepend the digit to the result at the current place value
24            result = placeValue * digit + result;
25            // Move to the next place value
26            placeValue *= 10;
27        }
28
29        // Remove the last digit from n
30        n = Math.floor(n / 10);
31    }
32
33    return result;
34}
35

Time and Space Complexity

  • Time Complexity: O(d), where d is the number of digits in n. The while loop iterates once per digit of n, since each iteration removes the last digit via n //= 10. All operations inside the loop (modulo, multiplication, addition, integer division) take constant time, so the total running time is proportional to the digit count d, which equals O(log n) in terms of the value of n.

  • Space Complexity: O(1). The algorithm only uses a fixed number of integer variables (k, ans, x, n) regardless of the input size, so the extra space required is constant.

Pattern Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall: Advancing the place value on every digit (including zeros)

The most frequent mistake is updating place_value unconditionally inside the loop, like this:

# WRONG
while n:
    digit = n % 10
    if digit:
        result = place_value * digit + result
    place_value *= 10   # ❌ advances even when the digit is 0
    n //= 10

Why it's wrong: This preserves the original position of every digit instead of compacting them. The zeros are not actually removed — they leave "holes" filled with 0 in the result.

Example trace with n = 1020030:

digitkept?place_value usedresult so far
0no10
3yes1030
0no10030
0no100030
2yes1000020030
0no10000020030
1yes10000001020030

The output is 1020030 — the original number, completely unchanged. The buggy code silently does nothing, which makes this especially dangerous: it passes the n = 999 test case (no zeros) and may slip through if your tests don't include numbers containing zeros.

Solution: Only multiply place_value by 10 inside the if digit: branch, so that each kept digit slides down into the slot a removed zero would have occupied:

# CORRECT
while n:
    digit = n % 10
    if digit:
        result = place_value * digit + result
        place_value *= 10   # ✅ advance only when a digit is kept
    n //= 10

Now n = 1020030 correctly yields 123.


Related Pitfall: Appending instead of prepending when building the result

Since digits are extracted from least significant to most significant, writing the natural-looking result = result * 10 + digit reverses the digit order:

# WRONG — produces the digits reversed
if digit:
    result = result * 10 + digit

For n = 105, this returns 51 instead of 15.

Solution: Either keep the place_value technique shown above (result = place_value * digit + result), which prepends each digit at the correct weight, or process the digits from most significant to least significant (e.g., via a string):

# Alternative string-based solution — order is preserved naturally
class Solution:
    def removeZeros(self, n: int) -> int:
        return int(str(n).replace("0", ""))

This avoids both pitfalls at once, at the cost of string conversion overhead. Note that int(...) is safe here because the problem guarantees n contains at least one nonzero digit, so the stripped string is never empty.

Ready to land your dream job?

Unlock your dream job with a 5-minute quiz for a personalized study roadmap!

Get My Roadmap
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Get a Personalized Study Roadmap:

Given a sorted array of integers and an integer called target, find the element that equals to the target and return its index. Select the correct code that fills the ___ in the given code snippet.

1def binary_search(arr, target):
2    left, right = 0, len(arr) - 1
3    while left ___ right:
4        mid = (left + right) // 2
5        if arr[mid] == target:
6            return mid
7        if arr[mid] < target:
8            ___ = mid + 1
9        else:
10            ___ = mid - 1
11    return -1
12
1public static int binarySearch(int[] arr, int target) {
2    int left = 0;
3    int right = arr.length - 1;
4
5    while (left ___ right) {
6        int mid = left + (right - left) / 2;
7        if (arr[mid] == target) return mid;
8        if (arr[mid] < target) {
9            ___ = mid + 1;
10        } else {
11            ___ = mid - 1;
12        }
13    }
14    return -1;
15}
16
1function binarySearch(arr, target) {
2    let left = 0;
3    let right = arr.length - 1;
4
5    while (left ___ right) {
6        let mid = left + Math.trunc((right - left) / 2);
7        if (arr[mid] == target) return mid;
8        if (arr[mid] < target) {
9            ___ = mid + 1;
10        } else {
11            ___ = mid - 1;
12        }
13    }
14    return -1;
15}
16

Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More