LeetCode 2710. Remove Trailing Zeros From a String Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2710. Remove Trailing Zeros From a String

Description

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 <= 1000
  • num consists of only digits.
  • num doesn't have any leading zeros.

Solutions

Solution 1: Traversal

We can traverse the string from the end to the beginning, stopping when we encounter the first character that is not 0. Then, we return the substring from the beginning to this character.

The time complexity is O(n), where n is the length of the string. Ignoring the space consumed by the answer string, the space complexity is O(1).

PythonJavaC++GoTypeScriptRust
class Solution: def removeTrailingZeros(self, num: str) -> str: return num.rstrip("0")(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !