-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path224.BasicCalculator.cpp
41 lines (37 loc) · 1.06 KB
/
224.BasicCalculator.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
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int calculate(string s) {
stack<int> nums;
int answer=0;
long long current_val=0, sign=1;
for (char c : s) {
if (isdigit(c)) {
current_val=10*current_val + c-'0';
}else if(c=='+'){
answer+=current_val*sign;
current_val=0;
sign=1;
}else if(c=='-'){
answer+=current_val*sign;
current_val=0;
sign=-1;
}else if(c=='('){
nums.push(answer);
nums.push(sign);
answer=0;
sign=1;
}else if(c==')' ){
answer+=current_val*sign;
current_val=0;
answer = answer*nums.top();
nums.pop();
answer= answer+nums.top();
nums.pop();
}
}
answer+=current_val*sign;
return answer;
}
};