-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0224-basic-calculator.cpp
More file actions
69 lines (64 loc) · 1.57 KB
/
0224-basic-calculator.cpp
File metadata and controls
69 lines (64 loc) · 1.57 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
#include <string>
#include <deque>
#include <iostream>
using namespace std;
class Solution
{
public:
int end_of_parenthesis(string s)
{
int cnt = 1;
int i = 1;
while (cnt != 0 && i < s.length())
{
if (s[i] == '(')
cnt++;
else if (s[i] == ')')
cnt--;
i++;
}
return --i;
}
int calculate(string s)
{
if (s.length() < 2)
return stoi(s);
int ans = 0;
char opr = '+';
int i = 0, j;
while (i < s.length())
{
while (s[i] == ' ')
i++;
if (s.length() > i)
{
if (s[i] == '(')
{
j = end_of_parenthesis(s.substr(i));
ans += (opr == '+' ? 1 : -1) * calculate(s.substr(++i, j - 1));
i += j;
}
else if (s[i] == '+' || s[i] == '-') { opr = s[i]; i++; }
else
{
j = s[i] - '0';
while (i+1 < s.length() && s[i+1] >= '0' && s[i+1] <= '9') {
j = j*10 + (s[i+1] - '0');
i++;
}
ans += (opr == '+' ? 1 : -1) * j;
i++;
}
}
}
return ans;
}
};
int main()
{
string s = "(1+(4+5+2)-3)+(6+8)";
// string s = " 2-1+2 ";
Solution st;
st.calculate(s);
// cout << st.end_of_parenthesis(s);// << s.substr(0, 16);
}