fork download
  1. object Main extends App {
  2. def factorial(i: Int): Int = if (i == 1) i else i * factorial(i - 1)
  3.  
  4. def calc(s: String): Double = {
  5. var list = Seq.empty[Double]
  6. s.split(" ").foreach(s => s match {
  7. case "+" =>
  8. val List(a, b, temp @ _*) = list
  9. list = (b + a) +: temp
  10. case "-" =>
  11. val List(a, b, temp @ _*) = list
  12. list = (b - a) +: temp
  13. case "*" | "x" =>
  14. val List(a, b, temp @ _*) = list
  15. list = (b * a) +: temp
  16. case "/" =>
  17. val List(a, b, temp @ _*) = list
  18. list = (b / a) +: temp
  19. case "//" =>
  20. val List(a, b, temp @ _*) = list
  21. list = (b.toInt / a.toInt).toDouble +: temp
  22. case "%" =>
  23. val List(a, b, temp @ _*) = list
  24. list = (b % a) +: temp
  25. case "^" =>
  26. val List(a, b, temp @ _*) = list
  27. list = math.pow(b, a) +: temp
  28. case "!" =>
  29. val List(a, temp @ _*) = list
  30. list = factorial(a.toInt).toDouble +: temp
  31. case _ => list = s.toDouble +: list
  32. })
  33. if (list.size > 1) throw new IllegalArgumentException
  34. else list.head
  35. }
  36. io.Source.stdin.getLines.foreach(l => println(calc(l)))
  37. }
Success #stdin #stdout 0.16s 322432KB
stdin
0.5 1 2 ! * 2 1 ^ + 10 + *
1 2 3 4 ! + - / 100 *
100 807 3 331 * + 2 2 1 + 2 + * 5 ^ * 23 10 558 * 10 * + + *
stdout
7.0
-4.0
1.80055823E10