HeatPulse

La4-1 Postfiks Notacija

Nov 12th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. Постфикс нотација Problem 1 (0 / 1)
  2. Да се напише алгоритам кој ќе врши евалуација на израз во постфикс нотација.
  3.  
  4. На влез се чита низа од знаци за изразот (стринг), а на излез се печати вредноста на изразот по евалуацијата.
  5.  
  6. Име на класата (Java): PostFixEvaluation
  7.  
  8. import java.io.BufferedReader;
  9. import java.io.InputStreamReader;
  10. import java.util.NoSuchElementException;
  11. import java.util.Stack;
  12.  
  13.  
  14. public class PostFixEvaluation {
  15.  
  16. public static void main(String[] args) throws Exception{
  17.  
  18. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  19.  
  20. String expression = br.readLine();
  21. char exp[] = expression.toCharArray();
  22.  
  23. System.out.println(result(exp));
  24.  
  25. br.close();
  26.  
  27. }
  28.  
  29. public static int result(char [] ch) {
  30.  
  31. Stack<Integer> intStack = new Stack<>();
  32.  
  33.  
  34. StringBuilder sb = new StringBuilder();
  35. for (int i=0; i<ch.length; ++i) {
  36.  
  37. if (Character.isDigit(ch[i])) {
  38.  
  39. if (Character.isDigit(ch[i+1])) {
  40. sb.append(ch[i]);
  41. continue;
  42. }
  43. else {
  44. sb.append(ch[i]);
  45. intStack.push(Integer.parseInt(sb.toString()));
  46. sb = new StringBuilder();
  47. }
  48.  
  49. }
  50.  
  51. else if (ch[i] == '+') {
  52. int num1 = intStack.pop();
  53. int num2 = intStack.pop();
  54. intStack.push(num1 + num2);
  55. }
  56. else if (ch[i] == '-') {
  57. int num1 = intStack.pop();
  58. int num2 = intStack.pop();
  59. intStack.push(num2 - num1);
  60. }
  61. else if (ch[i] == '*') {
  62. int num1 = intStack.pop();
  63. int num2 = intStack.pop();
  64. intStack.push(num1 * num2);
  65. }
  66. else if (ch[i] == '/') {
  67. int num1 = intStack.pop();
  68. int num2 = intStack.pop();
  69. intStack.push(num2 / num1);
  70. }
  71.  
  72. }
  73.  
  74. return intStack.pop();
  75.  
  76. }
  77.  
  78. }
  79.  
  80. Sample input
  81. 28 72 * 13 + 20 67 * +
  82. Sample output
  83. 3369
Add Comment
Please, Sign In to add comment