Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
def solveRPN(input: String): Double = {
input.split(" ").toList.foldLeft(List[Double]()){(out, in) =>
in match {
case "+" => out.dropRight(2) :+ (out.dropRight(1).last + out.last)
case "-" => out.dropRight(2) :+ (out.dropRight(1).last - out.last)
case "*" => out.dropRight(2) :+ (out.dropRight(1).last * out.last)
case "/" => out.dropRight(2) :+ (out.dropRight(1).last / out.last)
case "%" => out.dropRight(2) :+ (out.dropRight(1).last % out.last)
case _ => out :+ in.toDouble
}
}.head
}
println(solveRPN("1 3 +"))
println(solveRPN("1 3 + 5 2 - *"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment