Leetcode 227. Basic Calculator II
The problem is “227. Basic Calculator II” from LeetCode. The task is to implement a basic calculator to evaluate a simple expression string.
The expression string contains the following non-negative integers and operators +
, -
, *
, /
. The expression string is guaranteed to be valid and does not contain any leading or trailing spaces. Each integer in the string is non-negative and always less than 2^31
. The return value should be an integer.
*
and /
before +
and -
).Here’s an example:
"3+2*2"
7
currentNumber
to keep track of multi-digit numbers.currentNumber
.currentNumber
based on the last operator to the stack, then update the operator.+
and -
: Push the number directly to the stack.*
and /
: Perform immediate operations with the top of the stack.#include <iostream>
#include <string>
#include <stack>
class Solution {
public:
int calculate(std::string s) {
int n = s.size();
std::stack<int> stk;
char lastOperator = '+';
int currentNumber = 0;
for (int i = 0; i < n; ++i) {
char ch = s[i];
if (isdigit(ch)) {
currentNumber = currentNumber * 10 + (ch - '0');
}
if ((!isdigit(ch) && !isspace(ch)) || i == n - 1) {
if (lastOperator == '+') {
stk.push(currentNumber);
} else if (lastOperator == '-') {
stk.push(-currentNumber);
} else if (lastOperator == '*') {
int top = stk.top();
stk.pop();
stk.push(top * currentNumber);
} else if (lastOperator == '/') {
int top = stk.top();
stk.pop();
stk.push(top / currentNumber);
}
lastOperator = ch;
currentNumber = 0;
}
}
int result = 0;
while (!stk.empty()) {
result += stk.top();
stk.pop();
}
return result;
}
};
int main() {
Solution sol;
std::string input = "3+2*2";
int result = sol.calculate(input);
std::cout << "Result: " << result << std::endl; // Output: 7
return 0;
}
O(n)
O(n)
n
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?