• [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;
            
        }
    }
  • 相关阅读:
    Hello World
    JAVA环境变量配置
    基本的Dos命令
    博客的重要性
    MySQL——合并查询结果
    mysql中使用正则表达式查询
    MySQL高级查询
    MySQL之常用函数
    MySQL之多表操作
    MySQL之增删改查
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4713150.html
Copyright © 2020-2023  润新知