Welcome to Subscribe On Youtube

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)$.

  • class Solution {
        public long removeZeros(long n) {
            long k = 1;
            long ans = 0;
            while (n > 0) {
                long x = n % 10;
                if (x > 0) {
                    ans = k * x + ans;
                    k *= 10;
                }
                n /= 10;
            }
            return ans;
        }
    }
    
    
  • class Solution {
    public:
        long long removeZeros(long long n) {
            long long k = 1;
            long long ans = 0;
            while (n > 0) {
                long x = n % 10;
                if (x > 0) {
                    ans = k * x + ans;
                    k *= 10;
                }
                n /= 10;
            }
            return ans;
        }
    };
    
    
  • 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
    
    
  • func removeZeros(n int64) (ans int64) {
    	k := int64(1)
    	for n > 0 {
    		x := n % 10
    		if x > 0 {
    			ans = k*x + ans
    			k *= 10
    		}
    		n /= 10
    	}
    	return
    }
    
    
  • function removeZeros(n: number): number {
        let k = 1;
        let ans = 0;
        while (n) {
            const x = n % 10;
            if (x) {
                ans = k * x + ans;
                k *= 10;
            }
            n = Math.floor(n / 10);
        }
        return ans;
    }
    
    

All Problems

All Solutions