# leetcode 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


Note: Do not use the eval built-in library function.

public int calculate(String s) {
int i=0;
Stack<Character> op=new Stack<>();
Stack<Integer> num=new Stack<>();
while(i<s.length()){
while(s.charAt(i)==' '){
i++;
}
if(s.charAt(i)=='+'||s.charAt(i)=='-'||s.charAt(i)=='('){
op.push(s.charAt(i));
i++;
}
else if(s.charAt(i)==')'){
while(op.peek()!='('){
char temp=op.pop();
int num1=num.pop();
int num2=num.pop();
if(temp=='+'){
num.push(num1+num2);
}
else if(temp=='-') num.push(num2-num1);
}
op.pop();
while(!op.isEmpty()&&op.peek()!='('){
char temp=op.pop();
int num1=num.pop();
int num2=num.pop();
if(temp=='+'){
num.push(num1+num2);
}
else if(temp=='-') num.push(num2-num1);
}
i++;
}
else{
int k=0;
while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
k=k*10+(s.charAt(i)-'0');
i++;
}
if(!op.isEmpty()&&op.peek()=='+'){
op.pop();
int temp=num.pop();
num.push(temp+k);
}
else if(!op.isEmpty()&&op.peek()=='-'){
op.pop();
num.push(num.pop()-k);
}
else num.push(k);
}
}
return num.peek();
}

#### Leetcode 224: Basic Calculator

2015-06-19 00:59:08

#### LeetCode 770. Basic Calculator IV题目解析

2018-01-26 12:47:08

#### LeetCode-227. Basic Calculator II (JAVA)实现计算器 II

2017-04-30 09:54:02

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

2016-08-28 23:45:14

#### leetcode 227: Basic Calculator II

2015-06-26 03:18:48

#### [Leetcode] 770. Basic Calculator IV 解题报告

2018-03-21 16:40:42

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

2016-01-30 14:11:10

#### 【LeetCode】Basic Calculator 解题报告

2015-06-14 11:19:17

#### LeetCode224:Basic Calculator

2015-07-15 16:04:08

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

2016-04-05 04:45:01