Remove Trailing Zeros From a String
Problem
Given a positive numeric string num represented as a string, return num with any trailing zeros removed. A trailing zero is a '0' that appears at the end of the string.
num = "51230100""512301"def remove_trailing_zeros(num):
end = len(num)
while end > 0 and num[end - 1] == '0':
end -= 1
return num[:end]
function removeTrailingZeros(num) {
let end = num.length;
while (end > 0 && num[end - 1] === '0') {
end--;
}
return num.slice(0, end);
}
class Solution {
public String removeTrailingZeros(String num) {
int end = num.length();
while (end > 0 && num.charAt(end - 1) == '0') {
end--;
}
return num.substring(0, end);
}
}
string removeTrailingZeros(string num) {
int end = num.size();
while (end > 0 && num[end - 1] == '0') {
end--;
}
return num.substr(0, end);
}
Explanation
We only care about the zeros sitting at the very end of the string. Zeros in the middle (like the 0 in "512301") must stay. So the natural approach is to scan backwards from the last character and stop at the first non-zero digit.
We track an index end that marks where the kept portion stops. It starts at num.length (everything kept). While the character just before end is a '0', we move end one step left, effectively chopping that zero off.
The loop also guards end > 0 so it stops safely even if the whole string were zeros — it never walks off the front.
When the character before end is no longer a zero (or we have run out), we slice num[:end]. That substring is the original number with exactly the trailing zeros removed and every internal digit untouched.
Example: num = "51230100". Walking left, the last two characters are '0' so end drops from 8 to 6; the next character '1' stops the loop. num[:6] is "512301".