Evaluate a boolean expression represented as string in C++


In this problem, we are given a string exp that represents a boolean expression. Our task is to evaluate the boolean expression represented as String.

The valid characters in the expression are −

0 or 1 denoting the boolean value
& denoting AND operation

| denoting OR operation
^ denoting XOR operation

We need to solve this expression and return the result.

Let's take an example to understand the problem,

Input: str = 1&1|0^1^0&1

Output: 0

Explanation: 

1&1|0^1^0&1

1 AND 1 OR 0 XOR 1 XOR 0 AND 1

1 OR 0 XOR 1 XOR 0 AND 1
1 XOR 1 XOR 0 AND 1
0 XOR 0 AND 1
0 AND 1

0

Solution Approach:


A simple solution is to check the current values and then perform operations one by one. For this we will consider 3-3 characters of the string and then return their result.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int andOperation(int a, int b){
   return a & b;
}

int orOperation(int a, int b){
   return a | b;
}

int xorOperation(int a, int b){
   return a^b;
}

char solveExpression(string s) {
   
   int n = s.length();

   for (int i = 0; i < n; i += 2) {

      if (s[i + 1] == '&') {
            s[i + 2] = andOperation(s[i], s[i + 2]);
      }
      else if (s[i + 1] == '+') {
            s[i + 2] = orOperation(s[i], s[i + 2]);
      }
      else {
            s[i + 2] = xorOperation(s[i], s[i + 2]);
      }
   }
   return s[n - 1] ;
}

int main() {
   
   string expr = "0^1+0+1&1";
   cout<<"The result of expression "<<expr<<" is "<<solveExpression(expr);
   return 0;
}

Output −

The result of expression 0^1+0+1&1 is 1

Updated on: 22-Jan-2021

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements