[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/mJackie/leetcode/master/code/lc227.java [Back]  [Original]

package code;

import java.util.Stack;

/*
 * 227. Basic Calculator II
 * 
 * Medium
 * String
 * 
 *      + - * /  * / 
 * Tips
 */
public class lc227 {
    public int calculate(String s) {
        char[] chs = s.replace(" ","").toCharArray();
        int num = 0;
        char sign = '+';
        Stack st = new Stack();
        for (int i = 0; i < chs.length ; i++) {
            if(Character.isDigit(chs[i])){
                num = num * 10 + chs[i]-'0';
            }
            if( !Character.isDigit(chs[i]) || i==chs.length-1 ){    //
                if(sign=='+'){
                    st.push(num);
                }
                else if(sign=='-'){
                    st.push(-num);
                }
                else if(sign=='*'){
                    st.push(st.pop()*num);
                }
                else if(sign=='/'){
                    st.push(st.pop()/num);
                }
                num = 0;
                sign = chs[i];  //
            }
        }
        int res = 0;
        for(Integer i : st){
            System.out.println(i);
            res += i;
        }
        return res;
    }
}

Web Proxy Viewer  |  New URL  |  Original Page