Last active
November 3, 2021 06:46
-
-
Save dannymcgee/b244a19dd5fa96933810544b4f9e335c to your computer and use it in GitHub Desktop.
Evaluate Reverse Polish Notation (leetcode #150)
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
pub fn eval_rpn(tokens: &[&str]) -> i32 { | |
tokens | |
.iter() | |
.fold(vec![], |mut stack, token| match *token { | |
op @ ("+" | "-" | "*" | "/") => { | |
let rhs = stack.pop().unwrap(); | |
let lhs = stack.pop().unwrap(); | |
stack.push(match op { | |
"+" => lhs + rhs, | |
"-" => lhs - rhs, | |
"*" => lhs * rhs, | |
"/" => lhs / rhs, | |
_ => unreachable!(), | |
}); | |
stack | |
} | |
n => { | |
stack.push(n.parse().unwrap()); | |
stack | |
} | |
}) | |
.pop() | |
.unwrap() | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn example_1() { | |
let result = eval_rpn(&["2", "1", "+", "3", "*"]); | |
assert_eq!(result, 9); | |
} | |
#[test] | |
fn example_2() { | |
let result = eval_rpn(&["4", "13", "5", "/", "+"]); | |
assert_eq!(result, 6); | |
} | |
#[test] | |
fn example_3() { | |
let result = eval_rpn(&[ | |
"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+", | |
]); | |
assert_eq!(result, 22); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment