[LeetCode] Basic Calculator

224. Basic Calculator

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
int parse(string& s, int& i) {
int res = 0;
while(i < s.length() and isdigit(s[i])) {
res = res * 10 + (s[i++] & 0b1111);
}
return res;
}
int solution(string& s, int& i) {
int res = 0, sign = 1;
while(i < s.length() and s[i] != ')') {
if(s[i] == ' ') i++;
else if(s[i] == '(') res += solution(s,++i) * sign;
else if(s[i] == '-') {
sign = -1; i++;
} else if(s[i] == '+') {
sign = 1; i++;
} else {
res += parse(s,i) * sign;
}
}
i++;
return res;
}
public:
int calculate(string s) {
int i = 0;
return solution(s,i);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/16/PS/LeetCode/basic-calculator/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.