diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 86d27c2..dbe297c 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -136,4 +136,5 @@ mod p57_insert_interval; mod p452_minimum_number_of_arrows_to_burst_balloons; mod p71_simplify_path; mod p155_min_stack; -mod p150_evaluate_reverse_polish_notation; \ No newline at end of file +mod p150_evaluate_reverse_polish_notation; +mod p224_basic_calculator; \ No newline at end of file diff --git a/src/problem/p224_basic_calculator.rs b/src/problem/p224_basic_calculator.rs new file mode 100644 index 0000000..585c55b --- /dev/null +++ b/src/problem/p224_basic_calculator.rs @@ -0,0 +1,63 @@ +/** + * [224] Basic Calculator + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn calculate(s: String) -> i32 { + let mut operator_stack = vec![1]; + let mut result: i64 = 0; + let mut sign = 1; + + let s : Vec = s.chars().collect(); + + let mut i = 0; + + while i < s.len() { + if s[i] == ' ' { + i += 1; + } else if s[i] == '+' { + sign = *operator_stack.last().unwrap(); + i += 1; + } else if s[i] == '-' { + sign = -(*operator_stack.last().unwrap()); + i += 1; + } else if s[i] == '(' { + operator_stack.push(sign); + i += 1; + } else if s[i] == ')' { + operator_stack.pop(); + i += 1; + } else { + let mut num: i64 = 0; + + while i < s.len() && s[i].is_numeric() { + num = num * 10 + s[i].to_digit(10).unwrap() as i64; + i += 1; + } + + result += sign * num; + } + } + + result as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_224() { + assert_eq!(2, Solution::calculate("1 + 1".to_owned())); + assert_eq!(3, Solution::calculate(" 2-1 + 2 ".to_owned())); + assert_eq!(23, Solution::calculate("(1+(4+5+2)-3)+(6+8)".to_owned())); + assert_eq!(2147483647, Solution::calculate("2147483647".to_owned())); + } +}