2710. Remove Trailing Zeros From a String LeetCode Solution

In this guide, you will get 2710. Remove Trailing Zeros From a String LeetCode Solution with the best time and space complexity. The solution to Remove Trailing Zeros From a String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Remove Trailing Zeros From a String solution in C++
  4. Remove Trailing Zeros From a String solution in Java
  5. Remove Trailing Zeros From a String solution in Python
  6. Additional Resources
2710. Remove Trailing Zeros From a String LeetCode Solution image

Problem Statement of Remove Trailing Zeros From a String

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.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

2710. Remove Trailing Zeros From a String LeetCode Solution in C++

class Solution {
 public:
  string removeTrailingZeros(string num) {
    return regex_replace(num, regex("0+$"), "");
  }
};
/* code provided by PROGIEZ */

2710. Remove Trailing Zeros From a String LeetCode Solution in Java

class Solution {
  public String removeTrailingZeros(String num) {
    return num.replaceAll("0+$", "");
  }
}
// code provided by PROGIEZ

2710. Remove Trailing Zeros From a String LeetCode Solution in Python

class Solution:
  def removeTrailingZeros(self, num: str) -> str:
    return num.rstrip('0')
# code by PROGIEZ

Additional Resources

See also  2449. Minimum Number of Operations to Make Arrays Similar LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.