-
Notifications
You must be signed in to change notification settings - Fork 0
/
224.基本计算器.cpp
132 lines (118 loc) · 2.82 KB
/
224.基本计算器.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
* @lc app=leetcode.cn id=224 lang=cpp
*
* [224] 基本计算器
*/
// @lc code=start
#include <string>
#include <stack>
using namespace std;
class Solution
{
public:
int compute(stack<int> &numStack, stack<int> &opsStack)
{
int result = numStack.top();
numStack.pop();
if (opsStack.empty())
{
return result;
}
if (opsStack.top() == 1)
{
result += numStack.top();
}
else if (opsStack.top() == -1)
{
result -= numStack.top();
}
opsStack.pop();
numStack.pop();
return result;
}
int calculate(string s)
{
stack<int> numStack, opsStack;
int sign = 0; // 计算的标识位
int num = 0;
const int BEGIN = 0;
const int NUM = 1;
const int OPTS = 2;
int STATE = BEGIN;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == ' ')
continue;
switch (STATE)
{
case BEGIN:
if (s[i] >= '0' && s[i] <= '9')
{
STATE = NUM;
}
else
{
STATE = OPTS;
}
i--;
break;
case NUM:
if (s[i] >= '0' && s[i] <= '9')
{
num = num * 10 + s[i] - '0';
}
else
{
numStack.push(num);
if (sign == 1)
{
compute(numStack, opsStack);
}
num = 0;
STATE = OPTS;
i--;
}
break;
case OPTS:
if (s[i] == '+')
{
opsStack.push(1);
sign = 1;
}
else if (s[i] == '-')
{
opsStack.push(-1);
sign = 1;
}
else if (s[i] == '(')
{
STATE = NUM;
sign = 0;
}
else if (s[i] == ')')
{
compute(numStack, opsStack);
}
else if (s[i] >= '0' && s[i] <= '9')
{
STATE = NUM;
i--;
}
break;
default:
break;
}
}
if (num != 0)
{
numStack.push(num);
compute(numStack, opsStack);
}
if (num == 0 && numStack.empty())
{
return 0;
}
return numStack.top();
}
};
// @lc code=end