LeetCode 2710: Remove Trailing Zeros From a String Solution
Master LeetCode problem 2710 (Remove Trailing Zeros From a String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2710. Remove Trailing Zeros From a String
Problem Explanation
Explanation
To solve this problem, we can iterate over the input string num from right to left and find the index of the first non-zero digit. Then, we can extract the substring from the beginning of the input string up to that index to get the result without trailing zeros.
- Start iterating from the end of the input string
num. - Find the index of the first non-zero digit.
- Extract the substring from the beginning of the input string up to that index.
- Return the resulting string.
Time complexity: O(n), where n is the length of the input string num.
Space complexity: O(1)
Solution Code
class Solution {
public String removeTrailingZeros(String num) {
int index = num.length() - 1;
while (index >= 0 && num.charAt(index) == '0') {
index--;
}
return num.substring(0, index + 1);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2710 (Remove Trailing Zeros From a String)?
This page provides optimized solutions for LeetCode problem 2710 (Remove Trailing Zeros From a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2710 (Remove Trailing Zeros From a String)?
The time complexity for LeetCode 2710 (Remove Trailing Zeros From a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2710 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2710 in Java, C++, or Python.