# 224. Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open `(` and closing parentheses `)`, the plus `+` or minus sign `-`, non-negativeintegers and empty spaces ``.

Example 1:

``````Input: "1 + 1"
Output: 2
``````

Example 2:

``````Input: " 2-1 + 2 "
Output: 3
``````

Example 3:

``````Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23
``````

Note:

• You may assume that the given expression is always valid.
• Do not use the `eval` built-in library function.

``````class Solution {
public:
int calculate(string s) {
int res = 0, sign = 1, n = s.size();
stack<int> st;
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0') {
int num = 0;
while (i < n && s[i] >= '0') {
num = 10 * num + (s[i++] - '0');
}
res += sign * num;
--i;
} else if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
} else if (c == '(') {
st.push(res);
st.push(sign);
res = 0;
sign = 1;
} else if (c == ')') {
res *= st.top(); st.pop();
res += st.top(); st.pop();
}
}
return res;
}
};
``````

``````class Solution {
public:
int calculate(string s) {
int res = 0, num = 0, sign = 1, n = s.size();
stack<int> st;
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0') {
num = 10 * num + (c - '0');
} else if (c == '+' || c == '-') {
res += sign * num;
num = 0;
sign = (c == '+') ? 1 : -1;
} else if (c == '(') {
st.push(res);
st.push(sign);
res = 0;
sign = 1;
} else if (c == ')') {
res += sign * num;
num = 0;
res *= st.top(); st.pop();
res += st.top(); st.pop();
}
}
res += sign * num;
return res;
}
};
``````

``````class Solution {
public:
int calculate(string s) {
int res = 0, num = 0, sign = 1, n = s.size();
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0' && c <= '9') {
num = 10 * num + (c - '0');
} else if (c == '(') {
int j = i, cnt = 0;
for (; i < n; ++i) {
if (s[i] == '(') ++cnt;
if (s[i] == ')') --cnt;
if (cnt == 0) break;
}
num = calculate(s.substr(j + 1, i - j - 1));
}
if (c == '+' || c == '-' || i == n - 1) {
res += sign * num;
num = 0;
sign = (c == '+') ? 1 : -1;
}
}
return res;
}
};
``````

Basic Calculator IV

Basic Calculator III

Basic Calculator II

Evaluate Reverse Polish Notation

Different Ways to Add Parentheses

https://leetcode.com/problems/basic-calculator/

https://leetcode.com/problems/basic-calculator/discuss/62361/Iterative-Java-solution-with-stack

https://leetcode.com/problems/basic-calculator/discuss/62362/JAVA-Easy-Version-To-Understand!!!!!

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation