-
Notifications
You must be signed in to change notification settings - Fork 1
/
227.basic-calculator-ii.rs
68 lines (57 loc) · 1.69 KB
/
227.basic-calculator-ii.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* @lc app=leetcode id=227 lang=rust
*
* [227] Basic Calculator II
*/
// @lc code=start
use std::collections::HashSet;
impl Solution {
pub fn calculate(mut s: String) -> i32 {
let mut digits = vec![];
let mut ops = vec![];
let mut curr = 0;
s.push('*');
for ch in s.chars() {
if ch.is_ascii_digit() {
curr *= 10;
curr += ch.to_digit(10).unwrap_or_default() as i32;
} else if ch != ' ' {
match ops.pop() {
Some('*') => {
let prev = digits.pop().unwrap();
digits.push(prev * curr);
},
Some('/') => {
let prev = digits.pop().unwrap();
digits.push(prev / curr);
},
Some(op) => {
digits.push(curr);
ops.push(op);
},
None => {
digits.push(curr);
}
}
ops.push(ch);
curr = 0;
}
}
ops.pop();
// println!("digits: {:?}, ops: {:?}, curr: {}", digits, ops, curr);
let mut ans = *digits.first().unwrap_or(&0);
for i in 0..digits.len()-1 {
match ops[i] {
'+' => {
ans += digits[i+1];
},
'-' => {
ans -= digits[i+1];
},
_ => {}
}
}
ans
}
}
// @lc code=end