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 a String INPUT String: num = "51230" '5' 0 '1' 1 '2' 2 '3' 3 '0' 4 Index positions Trailing Zero Input Value: num = "51230" Length: 5 characters Goal: Remove trailing '0's ALGORITHM STEPS 1 Start from end Position i = length - 1 2 Check each char Is num[i] == '0'? 3 Move left if zero i = i - 1, repeat step 2 4 Return substring num[0...i] inclusive Trace: i=4: num[4]='0' (zero) skip i=3: num[3]='3' (non-zero) stop Last non-zero at index 3 Return num[0..3] = "5123" FINAL RESULT Trailing zeros removed: '5' '1' '2' '3' Output: "5123" OK - Verified! Before: "51230" (5 chars) After: "5123" (4 chars) 1 trailing zero removed Key Insight: Scan from the rightmost character moving left until finding a non-zero digit. The substring from index 0 to this position gives the result without trailing zeros. Time: O(n) | Space: O(1) - where n is the length of the string TutorialsPoint - Remove Trailing Zeros From a String | Find Last Non-Zero Position Approach
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