-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy path227. Basic Calculator II.cpp
86 lines (84 loc) · 2.27 KB
/
227. Basic Calculator II.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Lambda
class Solution {
private:
unordered_map<char, function<int(int,int)>>m {{'+', [](int a, int b){ return a + b ;}},
{'-', [](int a, int b){ return a - b ;}},
{'*', [](int a, int b){ return a * b ;}},
{'/', [](int a, int b){ return a / b ;}}};
public:
int calculate(string s) {
stringstream ss("+" + s + "+");
int sum(0), temp(0), num(0);
char op;
while(ss >> op){
ss >> num;
if(op == '+' || op == '-'){
sum += temp;
temp = m[op](0, num);
}
else temp = m[op](temp, num);
}
return sum;
}
};
// Or
class Solution {
public:
int calculate(string s) {
stringstream ss('+' + s + '+');
int temp = 0, num = 0, sum = 0;
char op = ' ';
while(ss >> op){
ss >> num;
if(op == '+'){
sum += temp;
temp = num;
}
if(op == '-'){
sum += temp;
temp = -num;
}
if(op == '*')
temp *= num;
if(op == '/')
temp /= num;
}
return sum;
}
};
// Using stack
class Solution {
public:
int calculate(string s) {
s += '+';
stack<int>stk;
int tmp = 0;
char op = '+';
for(int i = 0; i < s.size(); i++){
char c = s[i];
if(c == ' ') continue;
if(isdigit(c)) tmp = tmp*10 + c - '0';
if(!isdigit(c)){
if(op == '+')
stk.push(tmp);
else if(op == '-')
stk.push(-tmp);
else if(op == '*'){
int n = stk.top();
stk.pop();
stk.push(n*tmp);
}
else if(op == '/'){
int n = stk.top();
stk.pop();
stk.push(n/tmp);
}
op = c;
tmp = 0;
}
}
int res = 0;
while(!stk.empty()) res += stk.top(), stk.pop();
return res;
}
};