leetcode/
basic_calculator_ii.rs1pub struct Solution;
36
37enum Op {
38 Add,
39 Sub,
40 Mul,
41 Div,
42}
43
44impl Op {
45 fn eval(&self, a: i32, b: i32) -> i32 {
46 match self {
47 Op::Add => a + b,
48 Op::Sub => a - b,
49 Op::Mul => a * b,
50 Op::Div => a / b,
51 }
52 }
53}
54
55impl Solution {
56 pub fn calculate(s: String) -> i32 {
57 s.bytes()
58 .chain(std::iter::once(b'+'))
59 .fold((0, 0, 0, Op::Add), |(res, prev, cur, op), c| match c {
60 b'0'..=b'9' => (res, prev, cur * 10 + (c - b'0') as i32, op),
61 b'+' => (res + op.eval(prev, cur), 0, 0, Op::Add),
62 b'-' => (res + op.eval(prev, cur), 0, 0, Op::Sub),
63 b'*' => (res, op.eval(prev, cur), 0, Op::Mul),
64 b'/' => (res, op.eval(prev, cur), 0, Op::Div),
65 _ => (res, prev, cur, op),
66 })
67 .0
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::Solution;
74
75 #[test]
76 fn test() {
77 assert_eq!(Solution::calculate("3+2 *2".to_string()), 7);
78 assert_eq!(Solution::calculate("3/2 ".to_string()), 1);
79 assert_eq!(Solution::calculate("3+5/2".to_string()), 5);
80 }
81}