-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBasic calculator.cpp
More file actions
90 lines (63 loc) · 2.04 KB
/
Copy pathBasic calculator.cpp
File metadata and controls
90 lines (63 loc) · 2.04 KB
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
//not an efficent soln two pass is made
class Solution {
public:
int calculate(string s) {
deque<string>mstack;
char op = '.'; // starting point
stringstream ss;
int j=0;
while(j < s.size()){
if(s[j] == '+' || s[j] == '-'){
op = s[j];
ss<<s[j];
mstack.push_back(ss.str());
ss.clear(); ss.str(string(""));
j++;
}
else if(s[j]=='/' || s[j]== '*'){
op = s[j];
j++;
}
else if(s[j] != ' '){
while(j < s.size() && (s[j] != '+' && s[j] != '-' && s[j] != '*' && s[j] != '/' && s[j] != ' '))
ss<<s[j++];
if(op == '*' || op == '/'){
int op2;
int op1;
ss>>op2;
ss.clear(); ss.str(string(""));
ss<<mstack.back();
ss>>op1;
mstack.pop_back();
ss.clear(); ss.str(string(""));
ss<< (op == '/' ? op1/op2 : op1*op2);
mstack.push_back(ss.str());
ss.clear(); ss.str(string(""));
}
else{
mstack.push_back(ss.str());
ss.clear(); ss.str(string(""));
}
}
else
j++;
}
int result = 0;
while(mstack.size()!=1){
char fop = ' ';
int op1;
int op2;
ss<<mstack.front();mstack.pop_front();fop = mstack.front()[0];mstack.pop_front();
ss>>op1;ss.clear(); ss.str(string(""));
ss<<mstack.front();
ss>>op2;ss.clear(); ss.str(string(""));;mstack.pop_front();
ss<< (fop == '+' ? op1 + op2 : op1 - op2 );
mstack.push_front(ss.str());
ss.clear(); ss.str(string(""));
}
ss<<mstack.back();
ss>>result;
return result;
}
};
// one pass soln