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     }
  • 相关阅读:
    bzoj3159: 决战
    Codeforces Round #516 (Div. 1, by Moscow Team Olympiad) C
    Codeforces Round #516 (Div. 1, by Moscow Team Olympiad) B
    Codeforces Round #516 (Div. 1, by Moscow Team Olympiad) A
    loj 6401 字符串
    BZOJ5194 雪地靴
    BZOJ 4709 柠檬
    BZOJ 3343 魔法
    [8月16日绍兴]试剂
    设备塔
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7686258.html
Copyright © 2011-2022 走看看