227. Basic Calculator II
Problem:
Very similar to Basic Calculator I. The idea is to calculate the temp result whenever a sign is met and push into stack. If the prev sign is * or /, grab the stack top calc together.
For instance 3 + 2* 2.
+: calc +3 push into stack
*: calc +2 push into stack
string end: calc 2*2 push into stack
Solution:
Beware that the number might over 1 digit.
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: 5Analysis:
Very similar to Basic Calculator I. The idea is to calculate the temp result whenever a sign is met and push into stack. If the prev sign is * or /, grab the stack top calc together.
For instance 3 + 2* 2.
+: calc +3 push into stack
*: calc +2 push into stack
string end: calc 2*2 push into stack
Solution:
Beware that the number might over 1 digit.
class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack<>(); char sign = '+'; int num = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isDigit(c)) { num = num*10 + c - '0'; } if ("+-*/".indexOf(c) >= 0 || i == s.length() - 1) { switch(sign) { case '+': stack.push(num); break; case '-': stack.push(-num); break; case '*': stack.push(stack.pop() * num);break; case '/': stack.push(stack.pop() / num); break; } sign = c; num = 0; } } int res = 0; while(!stack.isEmpty()) { res += stack.pop(); } return res; } }
评论
发表评论