zoukankan      html  css  js  c++  java
  • LeetCode——Basic Calculator II

    Description:

    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.

    用两个操作栈来处理数据和操作符。先计算*和/然后变成加减法后再按顺序进行计算。

    public class Solution {
        public static int calculate(String s) {
            Stack<Integer> num = new Stack<>();
            Stack<Character> op = new Stack<>();
            op.push('+');
            int n = s.length();
            if(n < 1) return 0;
            for(int i=0; i<n; ) {
            	if(s.charAt(i) == ' ') {
            		i ++;
            	}
            	else if(isOp(s.charAt(i))) {
            		op.push(s.charAt(i));
            		i ++;
            	}
            	else {
            		int temp = 0;
            		while(i < n && isDigit(s.charAt(i))) {
            			temp = temp * 10;
            			temp += s.charAt(i) - '0';
            			i ++;
            		}
            		if(!op.empty() && (op.peek()=='*' || op.peek()=='/')) {
            			if(op.peek() == '*') {
            				temp *= num.pop();
            				op.pop();
            			}
            			else {
            				temp = num.pop() / temp;
            				op.pop();
            			}
            		}
            		num.push(temp);
            	}
            }
            int res = 0;
            while (!op.empty()) {  
            	int temp = num.peek();  
            	//System.out.println(temp);
            	if (op.peek() == '-') temp = -temp;  
            	res += temp;  
            	num.pop();  
            	op.pop();  
            }  
    
            return res;
            
        }
    	public static boolean isOp(char c) {
    		if(c == '+' || c == '-' || c == '*' || c == '/') {
    			return true;
    		}
    		else {
    			return false;
    		}
    	}
    	public static boolean isDigit(char c) {
    		if(c >= '0' && c <='9') {
    			return true;
    		}
    		else {
    			return false;
    		}
    	}
    }
    
  • 相关阅读:
    Mac下mysql出现错误:ERROR 1055 (42000)
    单表查询
    外键的变种 三种关系
    Java8中Lambda表达式详解
    Java中的比较器Comparable、Comparator
    Java创建线程的方法
    java日期格式化
    Docker容器如何修改hosts
    使用postman可以正常访问,但是在应用中返回415状态码
    使用tcpdump进行抓包
  • 原文地址:https://www.cnblogs.com/wxisme/p/4614857.html
Copyright © 2011-2022 走看看