-
Notifications
You must be signed in to change notification settings - Fork 1
/
leetcode0224-basic-calculator.cpp
47 lines (45 loc) · 1.16 KB
/
leetcode0224-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
/*
* Copyright (C) 2018 all rights reserved.
*
* Author: Houmin Wei <[email protected]>
*
* Source: https://leetcode.com/basic-calculator
*
*/
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
int calculate(string expression) {
stack<int> s;
int result = 0;
int number = 0;
int sign = 1;
for (char c : expression) {
if (isdigit(c)) {
number = number * 10 + c - '0';
} else if (c == '+') {
result += number * sign;
number = 0;
sign = 1;
} else if (c == '-') {
result += number * sign;
number = 0;
sign = -1;
} else if (c == '(') {
s.push(result);
s.push(sign);
sign = 1;
result = 0;
} else if (c == ')') {
result += sign * number;
number = 0;
result *= s.top(); s.pop();
result += s.top(); s.pop();
}
}
if (number != 0) result += sign * number;
return result;
}
};