-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path227_Basic_Calculator_II.cc
47 lines (44 loc) · 1.26 KB
/
227_Basic_Calculator_II.cc
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
class Solution {
public:
int calculate(string s) {
int result=0;
vector<int> nums;
int cur=0;
char op=NULL;
for(int i=0;i<=s.size();++i){
if(::isdigit(s[i])){
if(cur!=0){
cur=cur*10+(s[i]-'0');
}
else{
cur=s[i]-'0';
}
}
else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='\0'){
if(op=='+'||op==NULL){
nums.push_back(cur);
}
else if(op=='-'){
nums.push_back((-1)*cur);
}
else if(op=='*'){
int tmp=nums[nums.size()-1];
tmp=tmp*cur;
nums[nums.size()-1]=tmp;
}
else if(op=='/'){
int tmp=nums[nums.size()-1];
tmp=tmp/cur;
nums[nums.size()-1]=tmp;
}
cur=0;
op=s[i];
}
else continue;
}
for(int i=0;i<nums.size();++i){
result+=nums[i];
}
return result;
}
};