zoukankan      html  css  js  c++  java
  • 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
    

    Note: Do not use the eval built-in library function.

    以 3 + 2 * 2为例,这道题的重点是在循环到发现当前字符是*时,才对2进行处理 (push 2),然后更新sign。

    public class Solution {
        public int calculate(String s) {
            s = s.replace(" ", "");
            int num = 0;
            char sign = '+';
            Stack<Integer> stack = new Stack<>();
            for(int i = 0; i < s.length(); ++i) {
                if(Character.isDigit(s.charAt(i))) {
                    num = num * 10 + (s.charAt(i) - '0');
                }
                if(!Character.isDigit(s.charAt(i)) || i == s.length() - 1) {
                    if(sign == '+') {
                        stack.push(num);
                    } else if(sign == '-') {
                        stack.push(-num);
                    } else if(sign == '*') {
                        stack.push(stack.pop() * num);
                    } else if(sign == '/') {
                        stack.push(stack.pop() / num);;
                    } 
                    sign = s.charAt(i);
                    num = 0;
                }
            }
    
            int res = 0;
            for(int ele: stack) {
                res += ele;
            }
            return res;
        }
    }
  • 相关阅读:
    Scrapy爬虫之from import错误解决
    Mysql之IF嵌套和CASE WHEN的转化
    win10安装Redis
    win10安装elasticsearch
    Flink输出到JDBC
    Flink输出到Elasticsearch
    Flink输出到Redis
    IntelliJ IDEA 激活—2020年1月10号
    Flink输出到Kafka(两种方式)
    用C写一个功能较为完善的贪吃蛇小游戏
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4925026.html
Copyright © 2011-2022 走看看