fork download
  1. exp = '1+(2-3)/(4*5)'
  2. rpn = []
  3. stack = []
  4. operator = {
  5. '(' => 0,
  6. '+' => 1,
  7. '-' => 1,
  8. '*' => 2,
  9. '/' => 2,
  10. }
  11.  
  12. def isdigit(c)
  13. if c =~ /[0-9]/
  14. return true
  15. end
  16. return false
  17. end
  18.  
  19. exp.each_char do |e|
  20. if isdigit(e)
  21. rpn << e
  22. next
  23. end
  24. if e.class == String
  25. case e
  26. when ')'
  27. while stack[-1] != '('
  28. rpn << stack.pop
  29. end
  30. stack.pop
  31. next
  32. when '('
  33. stack << e
  34. next
  35. end
  36. if stack != []
  37. while operator[stack[-1]] >= operator[e]
  38. rpn << stack.pop
  39. if stack == []
  40. break
  41. end
  42. end
  43. end
  44. stack << e
  45. end
  46. end
  47.  
  48. while stack.length != 0
  49. rpn << stack.pop
  50. end
  51.  
  52. rpn.each do |e|
  53. print "#{e} "
  54. end
  55. print "\n"
Success #stdin #stdout 0.01s 7420KB
stdin
Standard input is empty
stdout
1 2 3 - 4 5 * / +