Difficulty: Easy | Acceptance: 79.60% | Paid: No Topics: String
Given a positive integer num represented as a string, return the string representation of the integer without any trailing zeros.
Table of Contents
- Examples
- Constraints
- Two Pointers Approach
- Built-in String Methods
- Iterative from End
Examples
Example 1:
Input: num = "51230100"
Output: "512301"
Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return "512301".
Example 2:
Input: num = "123"
Output: "123"
Explanation: Integer "123" has no trailing zeros, so we return "123".
Constraints
- 1 <= num.length <= 1000
- num consists of only digits.
- num doesn't have any leading zeros.
Two Pointers Approach
Intuition Use two pointers to find the position of the last non-zero character, then extract the substring from start to that position.
Steps
- Initialize a pointer at the end of the string
- Move the pointer backwards while the current character is ‘0’
- Return the substring from index 0 to the pointer position (inclusive)
python
class Solution:
def removeTrailingZeros(self, num: str) -> str:
n = len(num)
right = n - 1
while right >= 0 and num[right] == '0':
right -= 1
return num[:right + 1]Complexity
- Time: O(n) where n is the length of the string
- Space: O(n) for the resulting substring
- Notes: Simple and efficient, uses minimal extra space
Built-in String Methods
Intuition Leverage built-in string manipulation functions to remove trailing zeros directly.
Steps
- Use language-specific methods to strip trailing zeros
- In Python, use rstrip() method
- In Java, use lastIndexOf() or regex
- In JavaScript/TypeScript, use replaceEnd() or regex
python
class Solution:
def removeTrailingZeros(self, num: str) -> str:
return num.rstrip('0')Complexity
- Time: O(n) where n is the length of the string
- Space: O(n) for the resulting string
- Notes: Most concise solution, leverages built-in optimizations
Iterative from End
Intuition Iterate from the end of the string and build the result by counting trailing zeros, then slice accordingly.
Steps
- Count the number of trailing zeros by iterating from the end
- Use the count to determine the end index for slicing
- Return the substring excluding trailing zeros
python
class Solution:
def removeTrailingZeros(self, num: str) -> str:
count = 0
for i in range(len(num) - 1, -1, -1):
if num[i] == '0':
count += 1
else:
break
return num[:len(num) - count]Complexity
- Time: O(n) where n is the length of the string
- Space: O(n) for the resulting string
- Notes: Clear logic with explicit counting, easy to understand