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.

    Example 1:

    Input: "3+2*2"
    Output: 7
    

    Example 2:

    Input: " 3/2 "
    Output: 1

    Example 3:

    Input: " 3+5 / 2 "
    Output: 5

    Note:

    • You may assume that the given expression is always valid.
    • Do not use the eval built-in library function.

    Approach #1: Stack. [Java]

    class Solution {
        public int calculate(String s) {
            if (s == null || s.length() == 0) return 0;
            Stack<Integer> stack = new Stack();
            s += '+';
            char op = '+';
            for (int i = 0, n = 0; i < s.length(); ++i) {
                char c = s.charAt(i);
                if (c >= '0' && c <= '9') { n = n * 10 + c - '0'; continue; }
                if (c == ' ') continue;
                if (op == '+') stack.push(n);
                else if (op == '-') stack.push(-n);
                else if (op == '*') stack.push(stack.pop() * n);
                else if (op == '/') stack.push(stack.pop() / n);
                op = c;
                n = 0;
            }
            
            int ret = 0;
            while (!stack.empty()) 
                ret += stack.pop();
            
            return ret;
        }
    } 
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    【面试题】M
    【转】C/S,B/S区别
    【转】指针和引用的区别
    内联函数
    实习-随记
    【面试】http协议知识
    wenbenfenlei
    【面试】链表反转
    测试面试题2
    测试面试题
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10713258.html
Copyright © 2011-2022 走看看