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

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

    题目含义:实现一个计算器

     1     public int calculate(String s) {
     2         if (s == null || s.length() == 0) return 0;
     3         Stack<Integer> stack = new Stack<Integer>();
     4         int number = 0, sign = '+';
     5         for (int i = 0; i < s.length(); i++) {
     6             char letter = s.charAt(i);
     7             if (Character.isDigit(letter)) number = number * 10 + letter - '0';
     8             if ((!Character.isDigit(letter) && letter != ' ') || (i == s.length() - 1)) {
     9                 if (sign == '+') stack.push(number);
    10                 else if (sign == '-') stack.push(-number);
    11                 else if (sign == '*') stack.push(stack.pop() * number);
    12                 else if (sign == '/') stack.push(stack.pop() / number);
    13                 sign = letter;
    14                 number = 0;
    15             }
    16         }
    17         int result = 0;
    18         for (Integer value : stack) {
    19             result += value;
    20         }
    21         return result;   
    22     }
  • 相关阅读:
    SQL SERVER开窗函数
    SQL SERVER调优常用方法
    SQL SERVER其它函数
    SQL SERVER时间函数
    SQL SERVER字符串函数
    ptyhon技能树及其学习资源
    机器学习中的数学基础
    python-spider 第10题
    python-spider 第七关
    python-spider 第六关
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7686258.html
Copyright © 2011-2022 走看看