Remove Trailing Zeros From a String
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given a positive integer num represented as a string, return the integernum without trailing zeros as a string.
Examples
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 <= 1000numconsists of only digits.numdoesn't have any leading zeros.
Solution
Method 1 - String Rstrip or Manual Scan
Intuition
We want to remove all trailing zeros from the string. This can be done by scanning from the end or using built-in string methods.
Approach
- Start from the end of the string and move left until a non-zero is found.
- Return the substring up to that point.
- Or, use rstrip('0') in Python.
Code
C++
#include <string>
using namespace std;
string removeTrailingZeros(string num) {
int i = num.size() - 1;
while (i >= 0 && num[i] == '0') i--;
return num.substr(0, i+1);
}
Go
func removeTrailingZeros(num string) string {
i := len(num) - 1
for i >= 0 && num[i] == '0' {
i--
}
return num[:i+1]
}
Java
public class Solution {
public String removeTrailingZeros(String num) {
int i = num.length() - 1;
while (i >= 0 && num.charAt(i) == '0') i--;
return num.substring(0, i+1);
}
}
Kotlin
fun removeTrailingZeros(num: String): String {
var i = num.length - 1
while (i >= 0 && num[i] == '0') i--
return num.substring(0, i+1)
}
Python
def removeTrailingZeros(num: str) -> str:
return num.rstrip('0')
Rust
fn remove_trailing_zeros(num: &str) -> String {
let mut end = num.len();
let bytes = num.as_bytes();
while end > 0 && bytes[end-1] == b'0' {
end -= 1;
}
num[..end].to_string()
}
TypeScript
function removeTrailingZeros(num: string): string {
let i = num.length - 1;
while (i >= 0 && num[i] === '0') i--;
return num.slice(0, i + 1);
}
Complexity
- ⏰ Time complexity: O(N), where N is the length of num.
- 🧺 Space complexity: O(N), for the output string.