Basic Calculator
Thoughts
Code
/*
* @lc app=leetcode id=224 lang=cpp
*
* [224] Basic Calculator
*/
class Solution {
public:
int calculate(string str) {
int num = 0, sign = 1, res = 0;
stack<int> s;
for (const auto c : str) {
if (c >= '0' && c <= '9') num = num * 10 + (c - '0');
else if (c == '+') {
res += sign * num;
sign = 1;
num = 0;
} else if (c == '-') {
res += sign * num;
sign = -1;
num = 0;
} else if (c == '(') {
s.push(res);
s.push(sign);
sign = 1;
num = 0;
res = 0;
} else if (c == ')') {
int psign = s.top(); s.pop();
int pres = s.top(); s.pop();
res += sign * num;
res *= psign;
res += pres;
num = 0;
sign = 1;
}
}
if (num != 0) res += sign * num;
return res;
}
};
Analysis
Last updated