Created
July 18, 2015 03:48
-
-
Save shigemk2/3d512b8dc281b81eb89e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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