Watch 10 video solutions for Remove Zeros in Decimal Representation, a easy level problem involving Math, Simulation. This walkthrough by Programming Live with Larry has 434 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
You are given a positive integer n.
Return the integer obtained by removing all zeros from the decimal representation of n.
Example 1:
Input: n = 1020030
Output: 123
Explanation:
After removing all zeros from 1020030, we get 123.
Example 2:
Input: n = 1
Output: 1
Explanation:
1 has no zero in its decimal representation. Therefore, the answer is 1.
Constraints:
1 <= n <= 1015Problem Overview: You are given an integer n. The task is simple: remove every 0 digit from its decimal representation and return the resulting number. The relative order of the remaining digits must stay the same.
Approach 1: String Simulation (O(d) time, O(d) space)
Convert the number to a string and iterate through each character. Skip characters equal to '0' and append the rest to a new string or buffer. After the scan, convert the filtered string back to an integer. The key idea is that string traversal makes digit filtering trivial and avoids manual digit manipulation.
This approach is easy to implement and highly readable. Every digit is processed once, giving O(d) time where d is the number of digits. Extra space is O(d) for the temporary string. This solution relies on straightforward simulation of the digit removal process and is usually the fastest way to write correct code in interviews.
Approach 2: Mathematical Digit Construction (O(d) time, O(1) space)
Instead of converting to a string, process the number using arithmetic. Repeatedly extract digits with n % 10, skip the digit if it equals 0, and rebuild the result using positional multiplication. Because digits are extracted from right to left, you either build the number in reverse and flip it later, or track a multiplier to place digits correctly.
This method avoids additional memory and works entirely with integer operations. The loop runs once per digit, so the time complexity remains O(d) and the extra space is O(1). This solution highlights comfort with math operations and manual digit manipulation, which is common in problems involving decimal representation.
Recommended for interviews: Both approaches run in linear time relative to the number of digits. The string-based simulation is typically expected because it is concise and less error-prone. Showing the mathematical version demonstrates deeper understanding of number manipulation and simulation techniques, which interviewers often appreciate for follow-up discussion.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| String Simulation | O(d) | O(d) | Best for clarity and quick implementation using string filtering |
| Mathematical Digit Construction | O(d) | O(1) | When avoiding extra memory or practicing digit manipulation |