(Stack)Basic Calculator I && II

Basic Calculator I

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.

参考leetcode的解法:

// "(1+(4+5+2)-3)+(6+8)" = 23
public static int calculate(String s) {
Stack<Integer> stack = new Stack<Integer>();
int sign = 1; //表示正负
int number = 0; //存储数值
int result = 0;
for(int i = 0; i<s.length(); i++){
char c = s.charAt(i);
switch (c) {
//遇到运算符时,把前面的数值带上其前面的运算符加到结果上
case '+':
result += sign * number;
number = 0;
sign = 1;
break;
case '-':
result += sign * number;
number = 0;
sign = -1;
break;
case '(': //c='('时相当于开始一个新表达式,把原来的结果和符号存入栈中
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
number = 0;
break;
case ')': //把当前的表达式结果运算完,加上符号累加到原来的结果
result += sign * number;
result *= stack.pop();
result += stack.pop();
number = 0;
break;
case ' ':
break;
default:
number = number * 10 + (c - '0');
break;
}
}
if(number != 0)
result += sign * number;
return result;
}

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

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

参考leetcode的解法:

// 1+2*3
public static int calculate(String s) {
Stack<Integer> stack = new Stack<Integer>();
char sign = '+';
int number = ;
int result = ;
for(int i=; i<s.length(); i++){
char c = s.charAt(i);
if(Character.isDigit(s.charAt(i))){ //读取数值
number = number * + c - '';
}
//当字符为运算符或者到达表达式末尾时
if(!Character.isDigit(c) && ' ' != c || i == s.length() - ){
switch (sign) { //判断前一个运算符,跟I的本质区别
case '+':
stack.push(number);
break;
case '-':
stack.push(-number);
break;
case '*': //当上一个运算符为*或者/,取出栈顶数进行运算后再放入栈中
stack.push(stack.pop()*number);
break;
case '/':
stack.push(stack.pop()/number);
break;
}
number = ;
sign = c;
}
}
for(Integer i : stack){
result += i;
}
return result;
}
上一篇:刘庆峰年会演讲:科大讯飞的三层生态框架是如何建成的?


下一篇:Cardinality (基数)