/
224-Basic-Calculator.cpp
55 lines (52 loc) · 1.54 KB
/
224-Basic-Calculator.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public:
int calculate(string s) {
stack<string> tokens;
int pos = 0;
string token;
while (findNextToken(s, token, pos)){
if (token == ")"){
int val = calSimple(tokens);
tokens.pop(); // "("
ostringstream oss;
oss << val;
tokens.push(oss.str());
}else{
tokens.push(token);
}
}
return calSimple(tokens);
}
int calSimple(stack<string>& tokens){
int result = 0;
for (;;){
int num = strtoul(tokens.top().c_str(), NULL, 10);
tokens.pop();
if (tokens.empty() || tokens.top() == "("){
return result + num;
}
string op = tokens.top();
tokens.pop();
result = (op == "+")? result + num : result - num;
}
return result;
}
bool findNextToken(string& s, string& token, int& pos){
for (int i = pos; i < s.size(); i++){
if (s[i] == ' ') continue;
if (!('0' <= s[i] && s[i] <= '9')){
// +, -, (, )
token = s.substr(i,1);
pos = i + 1;
return true;
}
// num
int end = i;
while ( end + 1 < s.size() && '0' <= s[end + 1] && s[end + 1] <= '9') ++end;
token = s.substr(i, end - i + 1);
pos = end + 1;
return true;
}
return false;
}
};