leetcode-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.
解析:
代码解析:
package leetcode;
import java.util.Stack;
//不存符号,只存每一步的结果;
//主要思路:将+-当作数字的正负,将其push到栈中(最后出栈的时候一起按加法处理,优先级靠后,所以后运算);
//当遇到*/时,仅把当前num和stack中的最后进入的num相乘,结果继续放入stack中(/也一样)(优先级靠前,所以先运算)。
//符合这个场景 --> stack
public class BasicCalculator {
public static int calculate(String s) {
int len;
if(s==null || (len = s.length())==0) return 0;
Stack<Integer> stack = new Stack<Integer>();
int num = 0;
char sign = '+';
for(int i=0;i<len;i++){
if(Character.isDigit(s.charAt(i))){
num = num*10+s.charAt(i)-'0';
}
if((!Character.isDigit(s.charAt(i)) &&' '!=s.charAt(i)) || i==len-1){
if(sign=='-'){
stack.push(-num);
}
if(sign=='+'){
stack.push(num);
}
//注意pop和push的方法
if(sign=='*'){
stack.push(stack.pop()*num);
}
if(sign=='/'){
stack.push(stack.pop()/num);
}
sign = s.charAt(i);
num = 0;
}
}
int re = 0;
for(int i:stack){
re += i;
}
return re;
}
public static void main(String[] args) {
System.out.print(calculate("3+4-5*6/7"));
}
}