Remove Zeros in Decimal Representation Problem
#3726
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3726.
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 <= 10^15
Solution
Approach: Simulation
Read the digits of n from the lowest to the highest. Keep a multiplier k that is the place value for the next digit we keep (starting at 1). For every non-zero digit x, add x * k to the result and multiply k by 10; zero digits are skipped and do not move k.
Complexity: time O(d), space O(1), where d is the number of digits in n.
class Solution:
def removeZeros(self, n: int) -> int:
k = 1
ans = 0
while n:
x = n % 10
if x:
ans = k * x + ans
k *= 10
n //= 10
return ans