aboutsummaryrefslogtreecommitdiff
path: root/basic_calculator.rs
blob: d33a18c87ddfef5ee6289a46820f19eb8642cb91 (plain)
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
struct Solution;

impl Solution {
    pub fn calculate(s: String) -> i32 {
        let mut sp: Vec<i32> = Vec::new();
        let (mut ans, mut num, mut sign) = (0, 0, 1);
        sp.push(sign);
        for ch in s.chars() {
            match ch {
                ' ' => {}
                '+' | '-' => {
                    ans += num * sign;
                    sign = sp.last().unwrap() * if ch == '+' {1} else {-1};
                    num = 0;
                }
                '(' => {sp.push(sign);}
                ')' => {sp.pop();}
                _ => {num * 10 + (ch as i32 - '0' as i32)}
            };
        }
        ans += num * sign;
        ans
    }
}

fn main() {
    let s = String::from("1 + 1");
    print!("{}", Solution::calculate(s));
}