• 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
    // put all the number into stack 
    // if + num -> stack
    // if - -num -> stack
    // if *,/ pop()/num
    public class Solution {
        public int calculate(String s) {
            if(s == null || s.length()== 0) return 0;
            int res = 0;
            int curNum = 0;
            char sign = '+';
            Stack<Integer> stack = new Stack<>();
            for(int i = 0 ; i < s.length(); i++){
                char temp = s.charAt(i);
                if(temp == ' ') continue;
                else if(Character.isDigit(temp)){
                    curNum = curNum * 10 + temp - '0';
                }
                else if(temp == '+'){
                    stack.push(operation(sign, curNum, stack));
                    curNum = 0;
                    sign = '+';
                }
                else if(temp == '-'){
                    stack.push(operation(sign, curNum, stack));
                    curNum = 0;
                    sign = '-';
                }
                else if(temp == '*'){
                    stack.push(operation(sign, curNum, stack));
                    curNum = 0;
                    sign = '*';
                }
                 else if(temp == '/'){
                    stack.push(operation(sign, curNum, stack));
                    curNum = 0;
                    sign = '/';
                }
            }
            res = operation(sign, curNum, stack);
            while(!stack.isEmpty()){
                res += stack.pop();
            }
            return res;
            
        }
        
        public int operation(char sign, int number, Stack<Integer> stack){
            if(sign == '+')
                return number;
            else if(sign == '-')
                return -number;
            else if(sign == '*'){
                if(!stack.isEmpty())
                    return stack.pop() * number;
            }
            else if(sign == '/'){
                if(!stack.isEmpty())
                    return stack.pop() / number;
            }
            return number;    
        }
    }
  • 相关阅读:
    swift3.0 coreData的使用-日记本demo
    Objective-C plist文件与KVC 的使用
    swift3.0 CoreGraphics绘图-实现画板
    Objective-C 使用核心动画CAAnimation实现动画
    Objectiv-C UIKit基础 NSLayoutConstraint的使用(VFL实现)
    Objectiv-c
    C语言基础
    C语言基础
    swift 3.0 基础练习 面向对象 类的扩展
    myIsEqualToString
  • 原文地址:https://www.cnblogs.com/joannacode/p/6120691.html
Copyright © 2020-2023  润新知