
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Program to evaluate Boolean expression from a string in Python?
- Program to evaluate s-expression as string in Python
- Parsing A Boolean Expression in Python
- Divide large number represented as string in C++ Program
- Evaluating a string as a mathematical expression in JavaScript
- Evaluation of Boolean expression
- Evaluate Postfix Expression
- Program to expand string represented as n(t) format in Python
- Extract gender values as a string when it is stored in the table as a Boolean in MySQL
- Product of nodes at k-th level in a tree represented as string in C++
- JavaScript Convert a string to boolean
- Program to evaluate ternary expression in C++
- Parse a string to a Boolean object in Java
- String representation of Boolean in Java
- Why are numbers represented as objects in python?

Advertisements