Guest User

Untitled

a guest
Mar 22nd, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Solution {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. for (int a = 1; a <= 10; a++) {
  7. int n = sc.nextInt();
  8. String s = sc.next();
  9. String news = "";
  10. Stack<Character> stack = new Stack<Character>();
  11. for (int b = 0; b < n; b++) {
  12. if (s.charAt(b) >= '0' && s.charAt(b) <= '9') {
  13. news += s.charAt(b);
  14. } else if (s.charAt(b) == '(') {
  15. stack.add(s.charAt(b));
  16. } else if (s.charAt(b) == ')') {
  17. while (!(stack.peek() == '(')) {
  18. news += stack.pop();
  19. }
  20. stack.pop();
  21. } else if (s.charAt(b) == '+') {
  22. while (!(stack.peek() == '(')) {
  23. news += stack.pop();
  24. }
  25. stack.add(s.charAt(b));
  26. } else {
  27. stack.add(s.charAt(b));
  28. }
  29. }
  30. while (!stack.isEmpty()) {
  31. news += stack.pop();
  32. }
  33. Stack<String> stringstack = new Stack<String>();
  34. for (int b = 0; b < news.length(); b++) {
  35. if (news.charAt(b) >= '0' && news.charAt(b) <= '9') {
  36. stringstack.add(news.substring(b, b + 1));
  37. } else if (news.charAt(b) == '+') {
  38. int z = Integer.parseInt(stringstack.pop());
  39. int y = Integer.parseInt(stringstack.pop());
  40. int x = z + y;
  41. stringstack.add(String.valueOf(x));
  42. } else {
  43. int z = Integer.parseInt(stringstack.pop());
  44. int y = Integer.parseInt(stringstack.pop());
  45. int x = z * y;
  46. stringstack.add(String.valueOf(x));
  47. }
  48. }
  49. int sum = Integer.parseInt(stringstack.pop());
  50. System.out.println("#" + a + " " + sum);
  51. }
  52. sc.close();
  53. }
  54. }
Add Comment
Please, Sign In to add comment