Advertisement
krayddy

1.2.1.3(s) Infix => Postfix + Compute

Feb 20th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Linq;
  5.  
  6. namespace _1._2._1._3_s_
  7. {
  8. class Program
  9. {
  10. static void Main()
  11. {
  12. Console.WriteLine(Compute(Transform("(((((2-3)+1)*3)+1)*9)")));
  13. }
  14.  
  15. static string Transform(string str)
  16. {
  17. var postfix = string.Empty;
  18. var stack = new Stack<char>();
  19. foreach (var e in str)
  20. {
  21. if (char.IsDigit(e))
  22. postfix += e;
  23. else if (e == '(')
  24. stack.Push(e);
  25. else if (e == ')')
  26. {
  27. while (stack.Peek() != '(')
  28. {
  29. postfix += stack.Pop();
  30. }
  31. stack.Pop();
  32. }
  33. else if (IsOperation(e))
  34. {
  35. while (GetPriority(stack.Peek()) > e)
  36. {
  37. postfix += stack.Pop();
  38. }
  39. stack.Push(e);
  40. }
  41. }
  42. while (stack.Count != 0)
  43. {
  44. postfix += stack.Pop();
  45. }
  46. Console.WriteLine(postfix);
  47. return postfix;
  48. }
  49.  
  50. static bool IsOperation(char ch) => ch == '+' || ch == '-' || ch == '/' || ch == '*';
  51.  
  52. static int Compute(string str)
  53. {
  54. var stack = new Stack<int>();
  55. foreach (var e in str)
  56. {
  57. if (e <= '9' && e >= '0')
  58. {
  59. stack.Push(e - '0');
  60. continue;
  61. }
  62. switch (e)
  63. {
  64. case '+':
  65. stack.Push(stack.Pop() + stack.Pop());
  66. break;
  67. case '-':
  68. stack.Push(-stack.Pop() + stack.Pop());
  69. break;
  70. case '*':
  71. stack.Push(stack.Pop() * stack.Pop());
  72. break;
  73. case '/':
  74. stack.Push((1 / stack.Pop()) * stack.Pop());
  75. break;
  76. default:
  77. Console.WriteLine("wrong");
  78. throw new ArgumentException();
  79. }
  80. }
  81. return stack.Pop();
  82. }
  83.  
  84. public static int GetPriority(char operation)
  85. {
  86. switch (operation)
  87. {
  88. case '+': return 1;
  89. case '-': return 1;
  90. case '*': return 2;
  91. case '/': return 2;
  92. }
  93. return -1;
  94. }
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement