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;
	}

 

posted @ 2015-07-10 21:41  TonyLuis  阅读(383)  评论(0编辑  收藏  举报