227. Basic Calculator II

来源:互联网 发布:centos 6.5 安装php7 编辑:程序博客网 时间:2024/06/18 06:37
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.

以下是solution:

public 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++){        //1.        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){            //2.            if(sign=='-'){                stack.push(-num);            }            if(sign=='+'){                stack.push(num);            }            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;}

相比自己写的代码 主要有几点优化
1.获取表达式中的数字 
比如输入是 “2333+666"
我是这样做 从头开始找 找到第一个数字的作为start 也就是2 接下来向后找到第一个不是数字的 也就是+
那么在[2,+)之间 就是一个数字 也就是2333
solution是这样做 也是从开始找 只要找到一个数字 那么就num = num*10 + 当前数字
过程是这样
2
2*10+3
(2*10+3)*10 + 3
代码看起来比较简洁 也避免了用Integer.parseInt去转化
2.四则远算
我分了两步 遇到运算符 判断是不是高优先级的 也就是*和/ 如果是就直接运算 如果不是那么数字和运算符分别push进stack 等待后续运算
通过这样 乘除法优先运算 最后只剩下加减法
solution也是两步
判断运算符 如果是乘除 直接用上一个数字和当前数字运算 放入stack 如果是加减连带符号push进stack 变为正负数
最后 只要把stack中的元素sum就可以了 不区分加减法 看起来很清晰
算是一种对于运算的抽象吧