LeetCode 227. Basic Calculator II
原题链接在这里:https://leetcode.com/problems/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.
Example 1:
Input: "3+2*2" Output: 7
Example 2:
Input: " 3/2 " Output: 1
Example 3:
Input: " 3+5 / 2 " Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
题解:
It could apply the generic method. Use two level of operations. Calculate * and / first, accumlate the result into num2.
Then + and -, accumlate the result into num1.
The final result is num1 + o1 * num2.
When current char is digit, get the current number, perform * and /.
If current char is * and /, update operator 2.
If current char is + and -, perform previous + and - operation and update operator 1, reset num2, operator 2.
Time Complexity: O(n). n = s.length().
Space: O(1).
AC Java:
1 class Solution { 2 public int calculate(String s) { 3 if(s == null || s.length() == 0){ 4 return 0; 5 } 6 7 int num1 = 0; 8 int o1 = 1; 9 int num2 = 1; 10 int o2 = 1; 11 for(int i = 0; i<s.length(); i++){ 12 char c = s.charAt(i); 13 if(Character.isDigit(c)){ 14 int cur = c - '0'; 15 while(i+1 < s.length() && Character.isDigit(s.charAt(i+1))){ 16 cur = cur * 10 + s.charAt(i+1)-'0'; 17 i++; 18 } 19 20 num2 = o2 == 1 ? num2 * cur : num2 / cur; 21 }else if(c == '*' || c == '/'){ 22 o2 = c == '*' ? 1 : -1; 23 }else if(c == '+' || c == '-'){ 24 num1 = num1 + o1 * num2; 25 o1 = c == '+' ? 1 : -1; 26 27 num2 = 1; 28 o2 = 1; 29 } 30 } 31 32 return num1 + o1 * num2; 33 } 34 }