• 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
    // put all the number into stack 
    // if + num -> stack
    // if - -num -> stack
    // if *,/ pop()/num
    public class Solution {
        public int calculate(String s) {
            if(s == null || s.length()== 0) return 0;
            int res = 0;
            int curNum = 0;
            char sign = '+';
            Stack<Integer> stack = new Stack<>();
            for(int i = 0 ; i < s.length(); i++){
                char temp = s.charAt(i);
                if(temp == ' ') continue;
                else if(Character.isDigit(temp)){
                    curNum = curNum * 10 + temp - '0';
                }
                else if(temp == '+'){
                    stack.push(operation(sign, curNum, stack));
                    curNum = 0;
                    sign = '+';
                }
                else if(temp == '-'){
                    stack.push(operation(sign, curNum, stack));
                    curNum = 0;
                    sign = '-';
                }
                else if(temp == '*'){
                    stack.push(operation(sign, curNum, stack));
                    curNum = 0;
                    sign = '*';
                }
                 else if(temp == '/'){
                    stack.push(operation(sign, curNum, stack));
                    curNum = 0;
                    sign = '/';
                }
            }
            res = operation(sign, curNum, stack);
            while(!stack.isEmpty()){
                res += stack.pop();
            }
            return res;
            
        }
        
        public int operation(char sign, int number, Stack<Integer> stack){
            if(sign == '+')
                return number;
            else if(sign == '-')
                return -number;
            else if(sign == '*'){
                if(!stack.isEmpty())
                    return stack.pop() * number;
            }
            else if(sign == '/'){
                if(!stack.isEmpty())
                    return stack.pop() / number;
            }
            return number;    
        }
    }
  • 相关阅读:
    IE10 下兼容性问题
    前端面试题十九
    前端面试题十八
    前端面试题十七
    前端面试题十六
    前端面试题十五
    前端面试题十四
    前端面试题十三(兼容)
    前端面试题十二
    前端面试题十一
  • 原文地址:https://www.cnblogs.com/joannacode/p/6120691.html
Copyright © 2020-2023  润新知