3726. Remove Zeros in Decimal Representation
Description
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 <= 1015
Solutions
Solution 1: Simulation
We start from the lowest digit of \(n\) and check each digit one by one. If the digit is not zero, we add it to the result. We also need a variable to keep track of the current digit position in order to correctly construct the final integer.
Specifically, we can use a variable \(k\) to represent the current digit position, then check each digit from the lowest to the highest. If the digit is not zero, we multiply it by \(k\) and add it to the result, and then multiply \(k\) by 10 for the next digit.
In the end, we obtain an integer without any zeros.
The time complexity is \(O(d)\), where \(d\) is the number of digits in \(n\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |