-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path224.基本计算器.cpp
90 lines (84 loc) · 2.22 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
/*
* @lc app=leetcode.cn id=224 lang=cpp
*
* [224] 基本计算器
*/
// @lc code=start
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
class Solution {
public:
int calculate(string s) {
stack<int> stk;
int operand = 0;
int result = 0;
int sign = 1;
for(int i=0;i<s.size();i++)
{
char ch = s[i];
if(isdigit(ch)){
operand = 10 * operand + (int)(ch - '0');
}else if(ch == '+'){
result += sign * operand;
sign = 1;
operand = 0;
}else if(ch == '-'){
result += sign * operand;
sign = -1;
operand = 0;
}else if(ch == '('){
stk.push(result);
stk.push(sign);
sign = 1;
result = 0;
}else if(ch == ')'){
result += sign * operand;
result *= stk.top();//操作符
stk.pop();
result += stk.top();//操作数
stk.pop();
operand = 0;
}
}
return result + (sign * operand);
}
// int helper(string s)
// {
// stack<int> stk;
// int num = 0;
// char sign = '+';
// for(int i=0;i<s.size();i++){
// char c = s[i];
// if(isdigit(c)){
// num = 10*num + (c - '0');
// }
// if((!isdigit(c) && (c!=' '))|| i==s.size()-1){
// switch (sign)
// {
// case '+':
// stk.push(num);
// break;
// case '-':
// stk.push(-num);
// break;
// case '(':
// break;
// case ')':
// break;
// }
// sign = c;
// num = 0;
// }
// }
// int res = 0;
// while(!stk.empty()){
// res += stk.top();
// stk.pop();
// }
// return res;
// }
};
// @lc code=end