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.
和本博客下面连接的题目一模一样,这里再写一遍。
http://yuanhsh.iteye.com/blog/2194524
public int calculate(String s) { String[] arr = s.split("[\\+\\-\\*\\/]"); String[] ops = s.split("\\d+"); int n = arr.length; int[] nums = new int[n]; for(int i=0; i<n; i++) { nums[i] = Integer.parseInt(arr[i].trim()); } for(int i=1; i<n; i++) { char op = ops[i].trim().charAt(0); if(op == '-') { nums[i] = -nums[i]; } else if(op == '*') { nums[i] = nums[i-1]*nums[i]; nums[i-1] = 0; } else if(op == '/') { nums[i] = nums[i-1]/nums[i]; nums[i-1] = 0; } } int sum = 0; for(int num:nums) sum += num; return sum; }