# Middle-题目99：227. Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
“3+2*2” = 7
” 3/2 ” = 1
” 3+5 / 2 ” = 5

public class Solution {
public int calculate(String s) {
s=s.replace(" ","");
String[] nums = s.split("[\\+\\-\\*\\/]");
List<Integer> numberList = new ArrayList<>();
for(String num : nums)
int index = 0;
for (int i = 0; i<s.length(); i++) {
char ch = s.charAt(i);
if (ch == '+' || ch == '-')
index++;
else if (ch == '*' || ch == '/') {
int op1 = numberList.get(index);
int op2 = numberList.get(index+1);
numberList.remove(index);
numberList.remove(index);
}
}

int result = numberList.get(0); index = 1;
for(int i = 0;i<s.length();i++) {
char ch = s.charAt(i);
if(ch == '+' || ch == '-')
result = operate(result, ch, numberList.get(index++));
}
return result;

}
private Integer operate(int a, char op, int b) {
if(op=='+')
return a+b;
else if(op=='-')
return a-b;
else if(op=='*')
return a*b;
else
return a/b;
}
}

90ms,beats 13.83%,众数26ms,3.63%
Cmershen的碎碎念：

#### LeetCode 227. Basic Calculator II 解题报告【python】

2016-01-30 14:11:10

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

2016-04-05 04:45:01

#### 227. Basic Calculator II

2016-03-15 13:05:39

#### 227. Basic Calculator II**

2017-01-02 00:31:53

#### 227. Basic Calculator II

2017-12-10 17:58:02

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

2016-12-31 17:12:43

#### [leetcode]227. Basic Calculator II

2017-07-26 21:26:07

#### leetcode 227. Basic Calculator II

2016-03-31 14:07:40

#### 227. Basic Calculator II(unsolved)

2017-07-16 12:07:01

#### leetcode 227: Basic Calculator II

2015-06-26 03:18:48