Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 9abfdaa

Browse files
committed
solve #150
1 parent b0e85e3 commit 9abfdaa

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,4 @@ mod n0146_lru_cache;
144144
mod n0147_insertion_sort_list;
145145
mod n0148_sort_list;
146146
mod n0149_max_points_on_a_line;
147+
mod n0150_evaluate_reverse_polish_notation;
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* [150] Evaluate Reverse Polish Notation
3+
*
4+
* Evaluate the value of an arithmetic expression in <a href="http://en.wikipedia.org/wiki/Reverse_Polish_notation" target="_blank">Reverse Polish Notation</a>.
5+
*
6+
* Valid operators are +, -, *, /. Each operand may be an integer or another expression.
7+
*
8+
* Note:
9+
*
10+
*
11+
* Division between two integers should truncate toward zero.
12+
* The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
13+
*
14+
*
15+
* Example 1:
16+
*
17+
*
18+
* Input: ["2", "1", "+", "3", "*"]
19+
* Output: 9
20+
* Explanation: ((2 + 1) * 3) = 9
21+
*
22+
*
23+
* Example 2:
24+
*
25+
*
26+
* Input: ["4", "13", "5", "/", "+"]
27+
* Output: 6
28+
* Explanation: (4 + (13 / 5)) = 6
29+
*
30+
*
31+
* Example 3:
32+
*
33+
*
34+
* Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
35+
* Output: 22
36+
* Explanation:
37+
* ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
38+
* = ((10 * (6 / (12 * -11))) + 17) + 5
39+
* = ((10 * (6 / -132)) + 17) + 5
40+
* = ((10 * 0) + 17) + 5
41+
* = (0 + 17) + 5
42+
* = 17 + 5
43+
* = 22
44+
*
45+
*
46+
*/
47+
pub struct Solution {}
48+
49+
// submission codes start here
50+
51+
impl Solution {
52+
pub fn eval_rpn(tokens: Vec<String>) -> i32 {
53+
let mut stack: Vec<i32> = Vec::new();
54+
for t in tokens.iter() {
55+
if let Ok(num) = t.parse::<i32>() {
56+
stack.push(num);
57+
} else {
58+
let right = stack.pop().unwrap();
59+
let left = stack.pop().unwrap();
60+
match (t as &str) {
61+
"*" => { stack.push(left * right) },
62+
"+" => { stack.push(left + right) },
63+
"/" => { stack.push(left / right) },
64+
"-" => { stack.push(left - right) },
65+
_ => { unreachable!() },
66+
}
67+
}
68+
}
69+
stack.pop().unwrap()
70+
}
71+
}
72+
73+
// submission codes end
74+
75+
#[cfg(test)]
76+
mod tests {
77+
use super::*;
78+
79+
#[test]
80+
fn test_150() {
81+
assert_eq!(
82+
Solution::eval_rpn(vec_string!["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]),
83+
22
84+
);
85+
}
86+
}

0 commit comments

Comments
 (0)