2710. Remove Trailing Zeros From a String

Description

Given a positive integer num represented as a string, return the integer num without trailing zeros as a string.

 

Example 1:

Input: num = "51230100"
Output: "512301"
Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".

Example 2:

Input: num = "123"
Output: "123"
Explanation: Integer "123" has no trailing zeros, we return integer "123".

 

Constraints:

  • 1 <= num.length <= 1000
  • num consists of only digits.
  • num doesn't have any leading zeros.

Solutions

Solution 1

Python Code
1
2
3
class Solution:
    def removeTrailingZeros(self, num: str) -> str:
        return num.rstrip("0")

Java Code
1
2
3
4
5
6
7
8
9
class Solution {
    public String removeTrailingZeros(String num) {
        int i = num.length() - 1;
        while (num.charAt(i) == '0') {
            --i;
        }
        return num.substring(0, i + 1);
    }
}

C++ Code
1
2
3
4
5
6
7
8
9
class Solution {
public:
    string removeTrailingZeros(string num) {
        while (num.back() == '0') {
            num.pop_back();
        }
        return num;
    }
};

Go Code
1
2
3
4
5
6
7
func removeTrailingZeros(num string) string {
	i := len(num) - 1
	for num[i] == '0' {
		i--
	}
	return num[:i+1]
}

TypeScript Code
1
2
3
4
5
6
7
function removeTrailingZeros(num: string): string {
    let i = num.length - 1;
    while (num[i] === '0') {
        --i;
    }
    return num.substring(0, i + 1);
}

Rust Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
impl Solution {
    pub fn remove_trailing_zeros(num: String) -> String {
        let mut i = num.len() - 1;

        while num.chars().nth(i) == Some('0') {
            i -= 1;
        }

        num[..i + 1].to_string()
    }
}

Solution 2

Rust Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
impl Solution {
    pub fn remove_trailing_zeros(num: String) -> String {
        num.chars()
            .rev()
            .skip_while(|&c| c == '0')
            .collect::<String>()
            .chars()
            .rev()
            .collect::<String>()
    }
}