kacci97

Постфикс нотација

Nov 10th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.NoSuchElementException;
  4. import java.util.Stack;
  5.  
  6.  
  7. public class PostFixEvaluation {
  8.  
  9. public static void main(String[] args) throws Exception{
  10.  
  11. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  12.  
  13. String expression = br.readLine();
  14. char exp[] = expression.toCharArray();
  15.  
  16. System.out.println(result(exp));
  17.  
  18. br.close();
  19.  
  20. }
  21.  
  22. public static int result(char [] ch) {
  23.  
  24. Stack<Integer> intStack = new Stack<>();
  25.  
  26.  
  27. StringBuilder sb = new StringBuilder();
  28. for (int i=0; i<ch.length; ++i) {
  29.  
  30. if (Character.isDigit(ch[i])) {
  31.  
  32. if (Character.isDigit(ch[i+1])) {
  33. sb.append(ch[i]);
  34. continue;
  35. }
  36. else {
  37. sb.append(ch[i]);
  38. intStack.push(Integer.parseInt(sb.toString()));
  39. sb = new StringBuilder();
  40. }
  41.  
  42. }
  43.  
  44. else if (ch[i] == '+') {
  45. int num1 = intStack.pop();
  46. int num2 = intStack.pop();
  47. intStack.push(num1 + num2);
  48. }
  49. else if (ch[i] == '-') {
  50. int num1 = intStack.pop();
  51. int num2 = intStack.pop();
  52. intStack.push(num2 - num1);
  53. }
  54. else if (ch[i] == '*') {
  55. int num1 = intStack.pop();
  56. int num2 = intStack.pop();
  57. intStack.push(num1 * num2);
  58. }
  59. else if (ch[i] == '/') {
  60. int num1 = intStack.pop();
  61. int num2 = intStack.pop();
  62. intStack.push(num2 / num1);
  63. }
  64.  
  65. }
  66.  
  67. return intStack.pop();
  68.  
  69. }
  70.  
  71. }
Add Comment
Please, Sign In to add comment