-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic_Calculator_II.cpp
More file actions
44 lines (44 loc) · 1.04 KB
/
Basic_Calculator_II.cpp
File metadata and controls
44 lines (44 loc) · 1.04 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
// Basic Calculator II,用栈
int calculate_2(string s)
{
stack<int> ele_stack;
int length = s.length();
char sign = '+';
int num = 0;
for (int i = 0; i < length; i++)
{
//计算数字
if (isdigit(s[i]))
{
num = num * 10 + s[i] - '0';
}
//加减乘除
if (!isdigit(s[i]) && !isspace(s[i]) || i == length - 1)
{
if (sign == '+')
ele_stack.push(num);
else if (sign == '-')
ele_stack.push(-1 * num);
else
{
int value;
if (sign == '*')
value = ele_stack.top()*num;
else
value = ele_stack.top() / num;
ele_stack.pop();
ele_stack.push(value);
}
sign = s[i];
num = 0;
}
}
//累加
int result = num;
while (!ele_stack.empty())
{
result += ele_stack.top();
ele_stack.pop();
}
return result;
}