|
@@ -0,0 +1,52 @@
|
|
|
|
+
|
|
|
|
+struct Solution;
|
|
|
|
+impl Solution {
|
|
|
|
+ pub fn eval_rpn(tokens: Vec<String>) -> i32 {
|
|
|
|
+ let mut stack = vec![];
|
|
|
|
+ for i in 0..tokens.len() {
|
|
|
|
+ let v = &tokens[i][..];
|
|
|
|
+ match v {
|
|
|
|
+ "+" => {
|
|
|
|
+ let num1 = stack.pop().unwrap();
|
|
|
|
+ let num2 = stack.pop().unwrap();
|
|
|
|
+ stack.push(num1 + num2);
|
|
|
|
+ },
|
|
|
|
+ "-" => {
|
|
|
|
+ let num1 = stack.pop().unwrap();
|
|
|
|
+ let num2 = stack.pop().unwrap();
|
|
|
|
+ stack.push(num2 - num1);
|
|
|
|
+ },
|
|
|
|
+ "*" => {
|
|
|
|
+ let num1 = stack.pop().unwrap();
|
|
|
|
+ let num2 = stack.pop().unwrap();
|
|
|
|
+ stack.push(num1 * num2);
|
|
|
|
+ },
|
|
|
|
+ "/" => {
|
|
|
|
+ let num1 = stack.pop().unwrap();
|
|
|
|
+ let num2 = stack.pop().unwrap();
|
|
|
|
+ stack.push(num2 / num1);
|
|
|
|
+ },
|
|
|
|
+ _ => {
|
|
|
|
+ stack.push(v.parse::<i32>().unwrap())
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+ stack[0]
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+#[cfg(test)]
|
|
|
|
+mod tests {
|
|
|
|
+ use super::*;
|
|
|
|
+
|
|
|
|
+ #[test]
|
|
|
|
+ fn test_eval_rpn() {
|
|
|
|
+ let tokens = vec!["10","6","9","3","+","-11","*","/","*","17","+","5","+"];
|
|
|
|
+ let tokens = tokens.iter().map(|&x| x.to_string()).collect::<Vec<String>>();
|
|
|
|
+ let res = Solution::eval_rpn(tokens);
|
|
|
|
+ assert_eq!(res, 22);
|
|
|
|
+ }
|
|
|
|
+}
|