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;
        }
    }
  • 相关阅读:
    java 数字补齐0
    Ubuntu 12.04中文输入法的安装
    mac 更改word的默认显示比例为125
    接口测试的简介
    接口测试和功能测试的区别
    session、token、cookie的区别
    python接口自动化--get请求
    测试用例之正交排列法
    编写测试用例的方法
    jquery选择器
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4925026.html
Copyright © 2011-2022 走看看