-
Notifications
You must be signed in to change notification settings - Fork 0
/
Basic Calculator II.cpp
80 lines (71 loc) · 2.08 KB
/
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
class Solution {
public:
int calculate(string s) {
int result;
int size = (int)s.size();
stack<int> nums;
stack<char> opers;
int l=0,r =0;
for(int i = 0; i< size; i++){
if(s[i] == '+'||s[i] == '-'||s[i] == '*'||s[i] == '/'){ // if operater
int num2 = getnumber(l,r,s);
nums.push(num2);
if(!opers.empty()){
char op = opers.top();
if(op == '*'||op == '/') { // if * /
opers.pop();
calnum(nums, op);
// cout<<nums.top()<<endl;
}
if(!opers.empty() && (s[i] == '+' || s[i] == '-')){
calnum(nums, opers.top());
opers.pop();
}
}
opers.push(s[i]);
l = i+1;
r = i+1;
}
else r++;
}
int num = getnumber(l,r,s);
nums.push(num);
int osize = (int)opers.size();
for(int i =0; i<osize; i++){
char op = opers.top();
opers.pop();
calnum(nums, op);
}
result = nums.top();
return result;
}
void calnum(stack<int>& nums, char op){
int num2 = nums.top();
nums.pop();
int num1 = nums.top();
nums.pop();
switch(op){
case '+':
nums.push(num1+num2);
break;
case '-':
nums.push(num1-num2);
break;
case '*':
nums.push(num1*num2);
break;
case '/':
nums.push(num1/num2);
break;
}
return;
}
int getnumber(int l, int r, string& s){
int result = 0;
for(int k= l; k <r ; k++){
if(s[k] == ' ') continue;
result = result*10 + (s[k] - '0');
}
return result;
}
};