-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasic Calculator ||
34 lines (34 loc) Β· 1010 Bytes
/
Basic Calculator ||
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
class Solution {
public:
int calculate(string s) {
stack<int> myStack;
char sign = '+';
long long res = 0, tmp = 0;
for (unsigned int i = 0; i < s.size(); i++) {
if (isdigit(s[i]))
tmp = 10*tmp + s[i]-'0';
if (!isdigit(s[i]) && !isspace(s[i]) || i == s.size()-1) {
if (sign == '-')
myStack.push(-tmp);
else if (sign == '+')
myStack.push(tmp);
else {
int num;
if (sign == '*' )
num = myStack.top()*tmp;
else
num = myStack.top()/tmp;
myStack.pop();
myStack.push(num);
}
sign = s[i];
tmp = 0;
}
}
while (!myStack.empty()) {
res += myStack.top();
myStack.pop();
}
return res;
}
};