-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode-224-Basic_Calculator.cpp
60 lines (53 loc) · 1.4 KB
/
leetcode-224-Basic_Calculator.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <cstdlib>
#include <string>
class Solution {
public:
int calculate(std::string s, int& i) {
int res = 0,
temp_num=0;
char opt = 0;
for(; i<s.size(); ++i)
{
bool is_num = '0'<=s[i]&&s[i]<='9';
if(is_num)
{
temp_num = ((temp_num*10) + (s[i]-'0'));
}
if(!is_num || i==(s.size()-1))
{
if(s[i]=='(') {
temp_num = calculate(s, ++i);
++i;
}
if(opt==0 && (i==(s.size()-1) || s[i]!=' ')) {
res=temp_num;
} else if(i<(s.size()-1) && s[i]==' ') {
continue;
} else if(opt =='+') {
res+=temp_num;
} else if(opt =='-') {
res-=temp_num;
}
if(s[i]=='+'||s[i]=='-') {
opt=0;
temp_num=0;
opt = s[i];
} else if(s[i]==')') {
return res;
}
}
}
return res;
}
int calculate(std::string s) {
int i = 0;
return calculate(s,i);
}
};
int main(){
std::string s = "1 + 1";
auto res = Solution().calculate(s);
std::cout << res << std::endl;
return EXIT_SUCCESS;
}