Straightforward JAVA solution


  • 0
    Z
    public class Solution {
        //-1 for +, -2 for -, -3 for *, -4 for /
        
        public int calculate(String s) {
            LinkedList<Integer> ret = new LinkedList<Integer>();
            int curr=0;
            for(char c : s.toCharArray()) {
                if(c==' ')
                    continue;
                if(c=='+') {
                    ret.add(calcfirst(ret, curr));
                    ret.add(-1);
                    curr=0;
                    continue;
                }
                if(c=='-') {
                    ret.add(calcfirst(ret, curr));
                    ret.add(-2);
                    curr=0;
                    continue;
                }
                if(c=='*') {
                    ret.add(calcfirst(ret, curr));
                    ret.add(-3);
                    curr=0;
                    continue;
                }
                if(c=='/') {
                    ret.add(calcfirst(ret, curr));
                    ret.add(-4);
                    curr=0;
                    continue;
                }
                curr*=10;
                curr+=(c-'0');
            }
            ret.add(calcfirst(ret, curr));
            curr=ret.removeFirst();
            while(!ret.isEmpty()) {
                curr=calcfinal(ret,curr);
            }
            return curr;
        }
        
        private int calcfinal(LinkedList<Integer> ret, int curr) {
            if(ret.isEmpty())
                return curr;
            int s = ret.removeFirst();
            if(s==-1) {
                return curr+ret.removeFirst();
            }
            if(s==-2) {
                return curr-ret.removeFirst();
            }
            if(s==-3) {
                return curr*ret.removeFirst();
            }
            if(s==-4) {
                return curr/ret.removeFirst();
            }
            throw new IllegalArgumentException("wrong symbol "+new Integer(s).toString());
            //return 0;
        }
        
        private int calcfirst(LinkedList<Integer> ret, int curr) {
            if(ret.isEmpty())
                return curr;
            int s = ret.removeLast();
            if(s==-1) {
                ret.add(s);
                return curr;
            }
            if(s==-2) {
                ret.add(s);
                return curr;
            }
            if(s==-3) {
                return ret.removeLast()*curr;
            }
            if(s==-4) {
                return ret.removeLast()/curr;
            }
            throw new IllegalArgumentException("wrong symbol "+new Integer(s).toString());
            //return 0;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.