Here, we are going to see Remove Trailing Zeros From a String Solution of leetcode 2710 problem with code and example in C++.
You are 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".
Remove Trailing Zeros From a String Solution of leetcode 2710 in C++:
Here, we will be solving problem in multiple ways with code.
C++ code 1:
class Solution {
public:
string removeTrailingZeros(string num) {
while (num.length() > 0 && num[num.length() - 1] == '0') {
num.pop_back();
}
return num;
}
};
C++ code 2:
class Solution {
public:
string removeTrailingZeros(string num) {
stack<char> s;
string str = "";
bool flag = true;
for(int i = num.length() - 1; i >= 0; i--) {
if(flag && num[i] == '0') {
continue;
} else {
flag = false;
}
s.push(num[i]);
}
while(!s.empty()) {
str = str + s.top();
s.pop();
}
return str;
}
};
C++ code 3:
class Solution {
public:
string removeTrailingZeros(string num) {
int n = num.size();
for(int i = n-1; i >= 0; i--){
if(num[i] != '0'){
return num.substr(0, i+1);
}
}
return num;
}
};
Output:
Input: num = "51230100" Output: "512301"
To check more leetcode problem’s solution. Pls click given below link:
https://techieindoor.com/category/leetcode/
https://techieindoor.com/category/interview-questions/