-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path849.basic-calculator-iii.cpp
81 lines (73 loc) · 1.99 KB
/
849.basic-calculator-iii.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
// Tag: Stack, String, Simulation
// Time: O(N)
// Space: O(1)
// Ref: Leetcode-772
// Note: -
// Implement a basic calculator to evaluate a simple expression string.
//
//
// The expression string contains only non-negative integers, `+`, `-`, `*`, `/` operators , open `(` and closing parentheses `)` and empty spaces .
// The integer division should truncate toward zero.
//
// You may assume that **the given expression is always valid**.
// All intermediate results will be in the range of `[-2147483648, 2147483647]`
//
// **Example 1:**
// ```
// Input:"1 + 1"
// Output:2
// Explanation:1 + 1 = 2
// ```
//
//
// **Example 2:**
// ```
// Input:" 6-4 / 2 "
// Output:4
// Explanation:4/2=2,6-2=4
// ```
//
// Do not use the `eval` built-in library function.
class Solution {
public:
/**
* @param s: the expression string
* @return: the answer
*/
int calculate(string &s) {
// Write your code here
int i = 0;
return helper(s, i);
}
int helper(string &s, int &i) {
int left = 0; // stack except top
int right = 0; // stack top
int num = 0;
char op = '+';
while (i < s.size()) {
char ch = s[i];
if (isdigit(ch)) {
num = num * 10 + (ch - '0');
}
if ((!isdigit(ch) && ch != ' ') || i == s.size() - 1) {
if (ch == '(') {
i = i + 1;
num = helper(s, i);
}
switch (op) {
case '+': left += right; right = num; break;
case '-': left += right; right = -num; break;
case '*': right *= num; break;
case '/': right /= num; break;
}
op = ch;
num = 0;
if (ch == ')') {
break;
}
}
i++;
}
return left + right;
}
};