3726. Remove Zeros in Decimal Representation
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 gives123. - If
n = 105, removing all zeros gives15. - If
n = 999, there are no zeros to remove, so the answer is999.
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.
How We Pick the Algorithm
Why Simulation / Basic DSA?
This problem maps to Simulation / Basic DSA through a short path in the full flowchart.
Extracting digits, filtering out zeros, and rebuilding the number is a straightforward arithmetic simulation.
Open in FlowchartIntuition
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 % 10gives us the last digit ofn.n // 10chops 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 positionk, so we addk * xto 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 * xplaces digitxat the correct position (ones, tens, hundreds, ...).- Adding it to
ansinserts the digit without disturbing the digits already placed below it. k *= 10advances the place value — but only when a digit is kept. Ifxis0, 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:
| Step | n (before) | digit x = n % 10 | Action | ans | k |
|---|---|---|---|---|---|
| 1 | 1020030 | 0 | skip (zero) | 0 | 1 |
| 2 | 102003 | 3 | keep: ans = 1·3 + 0 = 3 | 3 | 10 |
| 3 | 10200 | 0 | skip (zero) | 3 | 10 |
| 4 | 1020 | 0 | skip (zero) | 3 | 10 |
| 5 | 102 | 2 | keep: ans = 10·2 + 3 = 23 | 23 | 100 |
| 6 | 10 | 0 | skip (zero) | 23 | 100 |
| 7 | 1 | 1 | keep: ans = 100·1 + 23 = 123 | 123 | 1000 |
After step 7, n becomes 0, the loop ends, and we return ans = 123.
Two details worth noticing in the trace:
-
Zeros never advance
k. In steps 1, 3, 4, and 6 the digit is0, so bothansandkstay frozen. That's why the digit2(originally in the thousands place of1020030) lands in the tens place of the answer — every kept digit slides down to fill the gaps the zeros left behind. -
Building from the right keeps order intact. Each kept digit is attached at place value
k, which is always larger than everything already inans. So even though we process digits in reverse (3 → 2 → 1), they end up in their original left-to-right order:1,2,3→123.
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
201class 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}
291class 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};
301/**
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}
35Time and Space Complexity
-
Time Complexity:
O(d), wheredis the number of digits inn. Thewhileloop iterates once per digit ofn, since each iteration removes the last digit vian //= 10. All operations inside the loop (modulo, multiplication, addition, integer division) take constant time, so the total running time is proportional to the digit countd, which equalsO(log n)in terms of the value ofn. -
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:
| digit | kept? | place_value used | result so far |
|---|---|---|---|
| 0 | no | 1 | 0 |
| 3 | yes | 10 | 30 |
| 0 | no | 100 | 30 |
| 0 | no | 1000 | 30 |
| 2 | yes | 10000 | 20030 |
| 0 | no | 100000 | 20030 |
| 1 | yes | 1000000 | 1020030 |
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 RoadmapGiven 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
121public 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}
161function 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}
16Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion If you prefer videos here's a video that explains recursion in a fun and easy way Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask him
Want a Structured Path to Master System Design Too? Don’t Miss This!