Remove Trailing Zeros From a String - Problem

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

Trailing zeros are the zeros at the end of a number. For example, the number "12300" has two trailing zeros.

Input & Output

Example 1 — Basic Case
$ Input: num = "51230"
Output: "5123"
💡 Note: The string has one trailing zero. Remove it to get "5123".
Example 2 — Multiple Trailing Zeros
$ Input: num = "40300"
Output: "403"
💡 Note: The string has two trailing zeros. Remove both to get "403".
Example 3 — No Trailing Zeros
$ Input: num = "123"
Output: "123"
💡 Note: No trailing zeros to remove, return the original string.

Constraints

  • 1 ≤ num.length ≤ 1000
  • num consists of only digits
  • num does not contain leading zeros

Visualization

Tap to expand
Remove Trailing Zeros From StringInput"51230"Original stringRemove zeros51230Last non-zeroRemoveOutput"5123"No trailing zeros
Understanding the Visualization
1
Input
String with trailing zeros
2
Process
Find last non-zero position
3
Output
String without trailing zeros
Key Takeaway
🎯 Key Insight: Work backwards from the end to efficiently find where to cut the string
Asked in
Amazon 25 Microsoft 18
25.8K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen