Remove Trailing Zeros From a String Problem
#2710
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2710.
Given a positive integer num represented as a string, return the integer num without trailing zeros as a string.
Example 1:
Input: num = "51230100"
Output: "512301"
Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".
Example 2:
Input: num = "123"
Output: "123"
Explanation: Integer "123" has no trailing zeros, we return integer "123".
Constraints:
1 <= num.length <= 1000numconsists of only digits.numdoesn't have any leading zeros.
Solution
Approach: Scan from the End
Walk backwards from the last character while it is '0'. The first non-zero character is the new end, so return the prefix of the string up to and including it.
Complexity: O(n) time and O(1) extra space.
class Solution:
def removeTrailingZeros(self, num: str) -> str:
return num.rstrip("0")