zoukankan      html  css  js  c++  java
  • Java for LeetCode 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
    解题思路:

    注意:测试中会出现“4*3/5”这样的情况,因此,可以用一个TempRes保存上一次运算的结果,TempOp表示距离本次运算符最近的+-运算符,具体看代码即可:

    	static public int calculate(String s) {
    		int res = 0, tempRes = 0, Option = 1, tempOp = 1;
    		for (int i = 0; i < s.length(); i++) {
    			switch (s.charAt(i)) {
    			case ' ':
    				break;
    			case '+':
    				Option = 1;
    				break;
    			case '-':
    				Option = -1;
    				break;
    			case '*':
    				Option = 2;
    				break;
    			case '/':
    				Option = 3;
    				break;
    			default:
    				int num = 0;
    				while (i < s.length() && Character.isDigit(s.charAt(i)))
    					num = num * 10 + s.charAt(i++) - '0';
    				i--;
    				switch (Option) {
    				case 1:
    					res += tempOp * tempRes;
    					tempRes = num;
    					tempOp = 1;
    					break;
    				case -1:
    					res += tempOp * tempRes;
    					tempRes = num;
    					tempOp = -1;
    					break;
    				case 2:
    					tempRes *= num;
    					break;
    				case 3:
    					tempRes /= num;
    				}
    
    			}
    		}
    		res += tempOp * tempRes;
    		return res;
    	}
    
  • 相关阅读:
    深入类的方法
    泛型集合
    深入C#数据类型
    深入.net框架
    错题
    详解Python Graphql
    深入理解分布式调度框架TBSchedule及源码分析
    30分钟闲置服务器建站(gitlab为例)
    Webpack开发指南
    mybatis-generator
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4637561.html
Copyright © 2011-2022 走看看