###### Hard-题目35：224. Basic Calculator

Hard-题目35：224. Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:
“1 + 1” = 2
” 2-1 + 2 ” = 3
“(1+(4+5+2)-3)+(6+8)” = 23

Cmershen的碎碎念：

public int calculate(String s) {
if (s.length() == 0) return 0;
s = "(" + s + ")";
int[] p = {0};
return eval(s, p);
}
// calculate value between parentheses
private int eval(String s, int[] p){
int val = 0;
int i = p[0];
int oper = 1; //1:+ -1:-
int num = 0;
while(i < s.length()){
char c = s.charAt(i);
switch(c){
case '+': val = val + oper * num; num = 0; oper = 1; i++; break;// end of number and set operator
case '-': val = val + oper * num; num = 0; oper = -1; i++; break;// end of number and set operator
case '(': p[0] = i + 1; val = val + oper * eval(s, p); i = p[0]; break; // start a new eval
case ')': p[0] = i + 1; return val + oper * num; // end current eval and return. Note that we need to deal with the last num
case ' ': i++; continue;
default : num = num * 10 + c - '0'; i++;
}
}
return val;
}

#### Leetcode 224: Basic Calculator

2015-06-19 00:59:08

#### LeetCode 224 Basic Calculator (后缀表达式 栈)

2016-08-28 23:45:14

#### 224. Basic Calculator | Java最短代码实现

2016-03-20 15:12:17

#### LeetCode 224. Basic Calculator（基本计算器）

2016-04-05 02:33:50

#### 224. Basic Calculator 227. Basic Calculator II

2016-12-31 17:12:43

#### LeetCode224:Basic Calculator

2015-07-15 16:04:08

#### 224. Basic Calculator

2016-03-22 10:43:42

#### leetcode 224. Basic Calculator

2016-03-31 11:43:32

#### [LeetCode]224. Basic Calculator

2016-03-04 22:29:23

#### [leetcode] 224. Basic Calculator

2015-11-24 18:48:05

## 不良信息举报

Hard-题目35：224. Basic Calculator