Boolean Postfix
InterviewTime limit1sMemory limit256 MB
Evaluate each postfix Boolean formula with AND, OR, XOR, and NOT using a stack and print 1 for true and 0 for false.
- Level
Easy3 of 10
- Topics
- Stack
- Solved
- No attempts yet
Problem
Logical Boolean expressions are usually written in infix notation, with the operators (∧, ∨) placed between their operands. For example, ((a∧b)∨¬c) is true when a and b are both true, or when c is false. Mary Lucy Margret writes the operator after its operands instead, which is called postfix notation. In her notation the same expression becomes (a b ∧ c ¬ ∨).
Write a program that parses and evaluates Boolean expressions written in Mary Lucy Margret's postfix notation. Every expression you are given is a correct and valid one.
Input
The first line contains one integer , the number of expressions. Each of the next lines contains one Boolean formula in postfix notation. The line starts with an integer , the number of tokens, followed by the tokens, each separated by a single space.
The tokens 1 and 0 denote the Boolean values true and false. Uppercase letters denote the operators. The possible tokens are:
- 1 for Boolean true,
- 0 for Boolean false,
- A for logical and,
- R for logical or,
- X for logical exclusive or,
- N for logical negation.
Output
Print lines. Each line contains 1 if the corresponding expression evaluates to true, and 0 otherwise.