Advertisement
Guest User

224. Basic Calculator

a guest
Jan 16th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. /**
  2. TC: O(N)
  3. SC: O(N)
  4. */
  5. class Solution {
  6. public int calculate(String s) {
  7. if(s == null || s.length() == 0)
  8. return 0;
  9.  
  10. int sign = 1;
  11. int num = 0 ;
  12. int result = 0;
  13. Stack<Integer> stack = new Stack<Integer>();
  14. stack.push(sign);
  15.  
  16. for(int i = 0; i< s.length(); i++){
  17. char c = s.charAt(i);
  18. if(c >= '0' && c <= '9'){
  19. num = num * 10 + (c - '0');
  20. }
  21. else if(c == '+' || c == '-'){
  22. result += sign * num;
  23. sign = stack.peek() * (c == '+'?1:-1);
  24. num = 0;
  25. }else if (c == '('){
  26. stack.push(sign);
  27. }else if (c == ')'){
  28. stack.pop();
  29. }
  30. }
  31. result += sign * num;
  32. return result;
  33. }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement