-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path224.basic-calculator.cpp
More file actions
60 lines (56 loc) · 1.31 KB
/
Copy path224.basic-calculator.cpp
File metadata and controls
60 lines (56 loc) · 1.31 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
/*
* @lc app=leetcode id=224 lang=cpp
*
* [224] Basic Calculator
*/
// @lc code=start
#include "bits/stdc++.h"
using namespace std;
class Solution {
public:
int calculate(string s) {
int result = 0;
int sum = 0;
int sign = 1;
stack<int> stk;
int n = s.size();
for (int i = 0; i < n; i++)
{
if (isdigit(s[i]))
{
sum = s[i] -'0';
while (i + 1 < n && isdigit(s[i + 1]))
{
sum = sum * 10 + (s[i + 1] -'0');
i++;
}
result += sum*sign;
}
else if (s[i] == '+')
{
sign = 1;
}
else if (s[i] == '-')
{
sign = -1;
}
else if (s[i] == '(')
{
stk.push(result);
stk.push(sign);
result = 0;
sign = 1;
}
else if(s[i] == ')')
{
int xsign = stk.top();
stk.pop();
int xresult = stk.top();
stk.pop();
result = result * xsign + xresult;
}
}
return result;
}
};
// @lc code=end