Convert a string such as (0 & (1 | 0) | 1) & (0 | 1) into it, the corresponding truth value

I found this on an interview forum and thought it was an interesting question. Is there an easy way to accomplish this task in C ++? For example, suppose we have a function declaration:

bool _transform(string x); 
/* x is a combination of (, ), 0, 1, &, and | such that all expressions 
   start with a open and ending brace, and the function evaluates the 
   strings actual truth value 
*/

Is there an effective and relatively easy way to do this? I was thinking about recursively closing parentheses, but the problem just seems difficult.

+4
source share
2 answers

. . " " - . : , . .

NB 1.

+2

. [ .]

For each character in the string
  If it a value (0 1)
    If top of stack is an operator
      Pop operator and value, evaluate
    Push value on the stack
  If it an operator (&|) push it on the stack
  If it a left parenthesis push it on the stack
  If it a right parenthesis pop the value and the LP, push the value
At end, pop the value off the stack.

, , . .

, , . infix " ".

+2

Source: https://habr.com/ru/post/1535666/


All Articles