|
| 1 | +/** |
| 2 | + * [227] Basic Calculator II |
| 3 | + * |
| 4 | + * Implement a basic calculator to evaluate a simple expression string. |
| 5 | + * |
| 6 | + * The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * |
| 11 | + * Input: "3+2*2" |
| 12 | + * Output: 7 |
| 13 | + * |
| 14 | + * |
| 15 | + * Example 2: |
| 16 | + * |
| 17 | + * |
| 18 | + * Input: " 3/2 " |
| 19 | + * Output: 1 |
| 20 | + * |
| 21 | + * Example 3: |
| 22 | + * |
| 23 | + * |
| 24 | + * Input: " 3+5 / 2 " |
| 25 | + * Output: 5 |
| 26 | + * |
| 27 | + * |
| 28 | + * Note: |
| 29 | + * |
| 30 | + * |
| 31 | + * You may assume that the given expression is always valid. |
| 32 | + * Do not use the eval built-in library function. |
| 33 | + * |
| 34 | + * |
| 35 | + */ |
| 36 | +pub struct Solution {} |
| 37 | + |
| 38 | +// submission codes start here |
| 39 | + |
| 40 | +impl Solution { |
| 41 | + pub fn calculate(s: String) -> i32 { |
| 42 | + let mut acc = 0_i64; |
| 43 | + let mut prev = 0_i64; |
| 44 | + let mut curr = 0_i64; |
| 45 | + let mut sign = 1; |
| 46 | + let mut has_prev = false; |
| 47 | + let mut multiple = true; |
| 48 | + for ch in s.chars() { |
| 49 | + match ch { |
| 50 | + '0'...'9' => { curr = 10 * curr + (ch as u8 - '0' as u8) as i64; }, |
| 51 | + '+' | '-' => { |
| 52 | + if has_prev { |
| 53 | + if multiple { |
| 54 | + curr = prev * curr; |
| 55 | + } else { |
| 56 | + curr = prev / curr; |
| 57 | + } |
| 58 | + has_prev = false; |
| 59 | + } |
| 60 | + acc += curr * sign; |
| 61 | + curr = 0; |
| 62 | + sign = if ch == '+' { 1 } else { -1 }; |
| 63 | + } |
| 64 | + '*' | '/' => { |
| 65 | + if has_prev { |
| 66 | + if multiple { |
| 67 | + curr = prev * curr; |
| 68 | + } else { |
| 69 | + curr = prev / curr; |
| 70 | + } |
| 71 | + } |
| 72 | + has_prev = true; |
| 73 | + prev = curr; |
| 74 | + curr = 0; |
| 75 | + multiple = if ch == '*' { true } else { false }; |
| 76 | + }, |
| 77 | + _ => {}, |
| 78 | + } |
| 79 | + } |
| 80 | + if has_prev { |
| 81 | + if multiple { |
| 82 | + curr = prev * curr; |
| 83 | + } else { |
| 84 | + curr = prev / curr; |
| 85 | + } |
| 86 | + } |
| 87 | + acc += sign * curr; |
| 88 | + acc as i32 |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +// submission codes end |
| 93 | + |
| 94 | + #[cfg(test)] |
| 95 | +mod tests { |
| 96 | + use super::*; |
| 97 | + |
| 98 | + #[test] |
| 99 | + fn test_227() { |
| 100 | + assert_eq!(Solution::calculate("3+2*2".to_owned()), 7); |
| 101 | + } |
| 102 | +} |
0 commit comments