Skip to content

Commit

Permalink
impl basic calculator II
Browse files Browse the repository at this point in the history
  • Loading branch information
SKTT1Ryze committed Apr 15, 2024
1 parent 858dc37 commit b60cf37
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion leetcode-rs/src/solutions/basic_calculator_ii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,27 @@ crate::derive_solution!(

impl SolutionImpl {
pub fn calculate(s: String) -> i32 {
todo!()
let mut stack = Vec::new();
let mut prev_sign = '+';
let mut num = 0;

for (idx, ch) in s.chars().enumerate() {
if ch.is_ascii_digit() {
num = num * 10 + ch.to_digit(10).unwrap() as i32;
}
if !ch.is_ascii_digit() && ch != ' ' || idx == s.len() - 1 {
match prev_sign {
'+' => stack.push(num),
'-' => stack.push(-num),
'*' => *stack.last_mut().unwrap() *= num,
'/' => *stack.last_mut().unwrap() /= num,
_ => {}
}
num = 0;
prev_sign = ch;
}
}

stack.iter().sum()
}
}

0 comments on commit b60cf37

Please sign in to comment.