[leedcode 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) {
        //使用sigh代表前一个运算符,利用栈保存加法或减法运算值,当遇到乘除时,
        //弹出栈顶进行运算,并将结果压栈,最后的结果时将栈中的元素进行相加
        int res=0;
        int sum=0;
        char sigh='+';
        Stack<Integer> stack=new Stack<Integer>();
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            if(Character.isDigit(c)){
                sum=sum*10+c-'0';
            }
            if(!Character.isDigit(c)&&s.charAt(i)!=' '||i==s.length()-1){
                 if(sigh=='+'){
                    stack.push(sum);
                }else if(sigh=='-'){
                    stack.push(-sum);
                }else if(sigh=='*'){
                    int t=stack.pop();
                    stack.push(t*sum);
                }else if(sigh=='/'){
                    int t=stack.pop();
                    stack.push(t/sum);
                }
                sum=0;
                sigh=c;
            }
        }
        while(!stack.isEmpty()){
            res+=stack.pop();
        }
        return res;
        
    }
}

 

posted @ 2015-08-08 14:54  ~每天进步一点点~  阅读(480)  评论(0编辑  收藏  举报