1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack<Integer>(); char[] cArr = s.toCharArray(); if (cArr.length == 0) return 0; char sign = '+'; int num = 0; for (int i = 0; i < cArr.length;) { if (Character.isDigit(cArr[i])) { num = num * 10 + (cArr[i] - '0'); } if ((!Character.isDigit(cArr[i]) && cArr[i] != ' ') || i == cArr.length - 1) { if (sign == '+') { stack.push(num); } else if (sign == '-') { stack.push(-1 * num); } else if (sign == '*') { int peek = stack.pop(); stack.push(peek * num); } else { int peek = stack.pop(); stack.push(peek / num); } sign = cArr[i]; num = 0; } i++; } int sum = 0; while (!stack.isEmpty()) { sum += stack.pop(); } return sum; } }
|