Problem#
Given a positive integer num
represented as a string, return the integer num
without trailing zeros as a string .
Examples#
Example 1#
1
2
3
Input: num = "51230100"
Output: "512301"
Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301" .
Example 2#
1
2
3
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.
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#
Cpp
Go
Java
Kotlin
Python
Rust
Typescript
1
2
3
4
5
6
7
8
#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 );
}
1
2
3
4
5
6
7
func removeTrailingZeros (num string ) string {
i := len(num ) - 1
for i >= 0 && num [i ] == '0' {
i --
}
return num [:i + 1 ]
}
1
2
3
4
5
6
7
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);
}
}
1
2
3
4
5
fun removeTrailingZeros (num: String): String {
var i = num.length - 1
while (i >= 0 && num[i] == '0' ) i--
return num.substring(0 , i+1 )
}
1
2
def removeTrailingZeros (num: str) -> str:
return num. rstrip('0' )
1
2
3
4
5
6
7
8
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()
}
1
2
3
4
5
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.