Answers for "Reverse Polish Notation (RPN) or postfic calculator"

0

Reverse Polish Notation (RPN) or postfic calculator

// Reverse Polish Notation (RPN) or postfix calculator

fn rpn_evaluator(expr: &str) -> i64 {
    let mut stack = vec![];
    for text in expr.split(" ") {
        match text {
            "+" => { 
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap(); 
                stack.push(a + b); 
            },
            "-" => { 
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap(); 
                stack.push(a - b); 
            },
            "*" => { 
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap(); 
                stack.push(a * b); 
            },
            "/" => { 
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap(); 
                stack.push(a / b); 
            },
            num => {
                stack.push(num.parse().unwrap());
            }
        }
    }
    stack.pop().unwrap()
}

fn main() {
    println!("RPN evaluator = {} ", rpn_evaluator("45 35 +"));   // 80
    println!("RPN evaluator = {} ", rpn_evaluator("4 8 + 6 5 - * 3 2 - 2 2 + * /"));   // 3
}
Posted by: Guest on October-09-2021

Browse Popular Code Answers by Language