Evaluate a boolean expression represented as string

Given a string consisting of only 0, 1, A, B, C where
A = AND
B = OR
C = XOR
Calculate the value of the string assuming no order of precedence and evaluation is done from left to right.
Constraints – The length of string will be odd. It will always be a valid string.
Example, 1AA0 will not be given as an input.

Examples:

Input : 1A0B1 Output : 1 1 AND 0 OR 1 = 1 Input : 1C1B1B0A0 Output : 0

Source : Microsoft online round for internship 2017

The idea is to traverse all operands by jumping a character after every iteration. For current operand str[i], check values of str[i+1] and str[i+2], accordingly decide the value of current subexpression.

Implementation:

C++

// C++ program to evaluate value of an expression. using namespace std; int evaluateBoolExpr(string s) int n = s.length(); // Traverse all operands by jumping // a character after every iteration. for ( int i = 0; i < n; i += 2) < // If operator next to current operand if (s[i + 1] == 'A' ) < if (s[i + 2] == '0' || s[i] == '0' ) // If operator next to current operand else if (s[i + 1] == 'B' ) < if (s[i + 2] == '1' || s[i] == '1' ) // If operator next to current operand // is XOR (Assuming a valid input) if (s[i + 2] == s[i]) return s[n - 1] - '0' ; // Driver code string s = "1C1B1B0A0" ; cout << evaluateBoolExpr(s);

Java

// Java program to evaluate value of an expression. public class Evaluate_BoolExp < // Evaluates boolean expression // and returns the result static int evaluateBoolExpr(StringBuffer s) int n = s.length(); // Traverse all operands by jumping // a character after every iteration. for ( int i = 0 ; i < n; i += 2 ) < // If operator next to current operand if ( i + 1 < n && i + 2 < n) if (s.charAt(i + 1 ) == 'A' ) < if (s.charAt(i + 2 ) == '0' || s.charAt(i) == 0 ) s.setCharAt(i + 2 , '0' ); s.setCharAt(i + 2 , '1' ); // If operator next to current operand else if ((i + 1 ) < n && s.charAt(i + 1 ) == 'B' ) < if (s.charAt(i + 2 ) == '1' || s.charAt(i) == '1' ) s.setCharAt(i + 2 , '1' ); s.setCharAt(i + 2 , '0' ); // If operator next to current operand // is XOR (Assuming a valid input) if (s.charAt(i + 2 ) == s.charAt(i)) s.setCharAt(i + 2 , '0' ); s.setCharAt(i + 2 , '1' ); return s.charAt(n - 1 ) - '0' ; // Driver code public static void main(String[] args) String s = "1C1B1B0A0" ; StringBuffer sb = new StringBuffer(s); System.out.println(evaluateBoolExpr(sb)); // This code is contributed by Sumit Ghosh

Python3

# Python3 program to evaluate value # of an expression. import math as mt def evaluateBoolExpr(s): # Traverse all operands by jumping # a character after every iteration. for i in range ( 0 , n - 2 , 2 ): # If operator next to current # operand is AND.''' if (s[i + 1 ] = = "A" ): if (s[i + 2 ] = = "0" or s[i] = = "0" ): # If operator next to current # operand is OR. else if (s[i + 1 ] = = "B" ): if (s[i + 2 ] = = "1" or s[i] = = "1" ): # If operator next to current operand # is XOR (Assuming a valid input) if (s[i + 2 ] = = s[i]): return ord (s[n - 1 ]) - ord ( "0" ) # Driver code s = "1C1B1B0A0" string = [s[i] for i in range ( len (s))] print (evaluateBoolExpr(string)) # This code is contributed # by mohit kumar 29

C#

// C# program to evaluate value // of an expression. using System; using System.Text; // Evaluates boolean expression // and returns the result public static int evaluateBoolExpr(StringBuilder s) int n = s.Length; // Traverse all operands by jumping // a character after every iteration. for ( int i = 0; i < n; i += 2) // If operator next to current // operand is AND. if (i + 1 < n && i + 2 < n) if (s[i + 1] == 'A' ) if (s[i + 2] == '0' || s[i] == 0) // If operator next to current // operand is OR. else if ((i + 1) < n && s[i + 1] == 'B' ) if (s[i + 2] == '1' || s[i] == '1' ) // If operator next to current operand // is XOR (Assuming a valid input) if (s[i + 2] == s[i]) return s[n - 1] - '0' ; // Driver code public static void Main( string [] args) string s = "1C1B1B0A0" ; StringBuilder sb = new StringBuilder(s); Console.WriteLine(evaluateBoolExpr(sb)); // This code is contributed by Shrikant13

PHP

// PHP program to evaluate value // of an expression. function evaluateBoolExpr( $s ) $n = strlen ( $s ); // Traverse all operands by jumping // a character after every iteration. for ( $i = 0; $i < $n ; $i += 2) // If operator next to current operand if (( $i + 1) < $n && $s [ $i + 1] == 'A' ) if ( $s [ $i + 2] == '0' || $s [ $i ] == '0' ) $s [ $i + 2] = '0' ; $s [ $i + 2] = '1' ; // If operator next to current operand else if (( $i + 1) < $n && $s [ $i + 1] == 'B' ) if ( $s [ $i + 2] == '1' || $s [ $i ] == '1' ) $s [ $i + 2] = '1' ; $s [ $i + 2] = '0' ; // If operator next to current operand // is XOR (Assuming a valid input) if (( $i + 2) < $n && $s [ $i + 2] == $s [ $i ]) $s [ $i + 2] = '0' ; $s [ $i + 2] = '1' ; return $s [ $n - 1] - '0' ; // Driver code $s = "1C1B1B0A0" ; echo evaluateBoolExpr( $s ); // This code is contributed // by Akanksha Rai

Javascript

// Javascript program to evaluate // value of an expression. // Evaluates boolean expression // and returns the result function evaluateBoolExpr(s) let n = s.length; // Traverse all operands by jumping // a character after every iteration. for (let i = 0; i < n; i += 2) // If operator next to current // operand is AND. if (i + 1 < n && i + 2 < n) if (s[i + 1] == 'A' ) if (s[i + 2] == '0' || // If operator next to current // operand is OR. else if ((i + 1) < n && s[i + 1] == 'B' ) if (s[i + 2] == '1' || s[i] == '1' ) // If operator next to current operand // is XOR (Assuming a valid input) if (s[i + 2] == s[i]) return (s[n - 1].charCodeAt() - '0' .charCodeAt()); // Driver code let s = "1C1B1B0A0" ; let sb = s.split( '' ); document.write(evaluateBoolExpr(sb) + "
" ); // This code is contributed by rameshtravel07 Output

Time Complexity: O(n)
Auxiliary Space: O(n)

GeeksforGeeks Like Article -->

Please Login to comment.

Similar Reads

Program to evaluate the expression (√X+1)^6 + (√X-1)^6

Given a number [Tex]X [/Tex]. The task is to find the value of the below expression for the given value of [Tex]X [/Tex]. [Tex](\sqrt[] +1)^6 + (\sqrt[]-1)^6[/Tex] Examples: Input: X = ?2 Output: 198 Explanation: [Tex]2[(\sqrt[])^6 + 15 (\sqrt[])^4 + 15\sqrt[])^2 + 1] [/Tex]= 198Input: X = 3 Output: 4160 Approach: The idea is to use

3 min read Evaluate the expression ( N1 * (N - 1)2 * . * 1N) % (109 + 7)

Given an integer N, the task is to find the value of the expression ( N1 * (N - 1)2 * . * 1N) % (109 + 7). Input: N = 1 Output: 1 Explanation: 11 = 1 Input: N = 4 Output: 288 Explanation: 41 * (4 - 1)2 * (4 - 2)3 * (4-3)4 = 4 * 9 * 8 * 1 = 288 Naive Approach: The simplest approach to solve this problem is to iterate over the range [1, N]. For eve

6 min read Evaluate an array expression with numbers, + and -

Given an array arr[] of string type which consists of strings "+", "-" and Numbers. Find the sum of the given array. Examples : Input : arr[] = <"3", "+", "4", "-", "7", "+", "13">Output : Value = 13 The value of expression 3+4-7+13 is 13. Input : arr[] = < "2", "+", "1", "-8", "+", "13">Output : Value = 8 Approach : First of all, initialize the

6 min read Minimum number of basic logic gates required to realize given Boolean expression

Given a string S of length N representing a boolean expression, the task is to find the minimum number of AND, OR, and NOT gates required to realize the given expression. Examples: Input: S = "A+B.C"Output: 2Explanation: Realizing the expression requires 1 AND gate represented by '.' and 1 OR gate represented by '+'. Input: S = "(1 - A). B+C"Output

4 min read What is Boolean Expression

In this article, we will see what is Boolean Expression. Before starting with the topic directly lets us see what is a Boolean expression. It is an expression that always yields two values either true or false when evaluated. If the condition is true then it will return true or false and vice versa. Let's take one simple example that will clear the

4 min read Print a sorted list of words represented by the expression under the given grammar

Given a string R(x) of length n representing an expression having the set of words under the given grammar: For every lowercase letter x, R(x) = For expressions e_1, e_2, . e_k with k?2, R() = R(e_1) ? R(e_2) ? . ? R(e_k).For expressions e_1 and e_2, R(e_1 + e_2) = , where + denotes c

14 min read Convert Infix expression to Postfix expression

Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +

13 min read Program to evaluate simple expressions

You are given a string that represent an expression of digits and operands. E.g. 1+2*3, 1-2+4. You need to evaluate the string or the expression. NO BODMAS is followed. If the expression is of incorrect syntax return -1. Test cases: a) 1+2*3 will be evaluated to 9. b) 4-2+6*3 will be evaluated to 24. c) 1++2 will be evaluated to -1(INVALID). Also,

11 min read Print all possible expressions that evaluate to a target

Given a string that contains only digits from 0 to 9, and an integer value, target. Find out how many expressions are possible which evaluate to target using binary operator +, - and * in given string of digits. Input : "123", Target : 6 Output : Input : “125”, Target : 7 Output : This problem can be solved by p

11 min read Evaluate the Fractions

Given a 2D array fractions[] and an array value [ ], which denotes that the value of the [Tex]fractions[i][0]/fractions[i][1] = values[i] [/Tex] for each index 'i', you have Q queries of the form [var1, var2]. Print the value of var1/var2 if it can be determined or else print -1. You may assume that there won't be any contradicting equations and th

13 min read Find the string among given strings represented using given encryption pattern

Given an array of strings arr[] of size N and an encrypted string str, the task is to find the correct string from the given array of strings whose encryption will give str where str is encrypted using the following rules: The starting characters form an integer representing the number of uppercase symbols In the decrypted string.The next 3 charact

8 min read Product of nodes at k-th level in a tree represented as string using Recursion

Prerequisite: Product of nodes at k-th level in a tree represented as stringGiven an integer ‘K’ and a binary tree in string format. Every node of a tree has value in range from 0 to 9. We need to find product of elements at K-th level from the root. The root is at level 0.Note: Tree is given in the form: (node value(left subtree)(right subtree))Ex

5 min read Reverse all the word in a String represented as a Linked List

Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence "I love Geeks for Geeks", the Linked List representation is given as: I-> ->l->o->v->e-> ->G->e->e->k->s-> ->f-

15 min read Product of nodes at k-th level in a tree represented as string

Given an integer 'K' and a binary tree in string format. Every node of a tree has value in range from 0 to 9. We need to find product of elements at K-th level from root. The root is at level 0. Note : Tree is given in the form: (node value(left subtree)(right subtree)) Examples: Input : tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" k = 2 Out

6 min read Find if a given string can be represented from a substring by iterating the substring “n” times

Given a string 'str', check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Examples: Input: str = "abcabcabc" Output: true The given string is 3 times repetition of "abc" Input: str = "abadabad" Output: true The given string is 2 times repetition of "abad" Input: str = "aabaabaabaab" Ou

15+ min read Sum of nodes at k-th level in a tree represented as string

Given an integer 'K' and a binary tree in string format. Every node of a tree has a value in the range of 0 to 9. We need to find the sum of elements at the K-th level from the root. The root is at level 0. Tree is given in the form: (node value(left subtree)(right subtree)) Examples: Input : tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" k =

9 min read Divide large number represented as string

Given a large number (represented as a string) which has to divide by another number (represented as int data type). The large number can be very large which does not even fit in long long in C++. The task is to find the division of these numbers. Examples: Input : number = 1260257 divisor = 37Output : 34061(See below diagram)Input : number = 1231

7 min read Check if a String Contains Only Alphabets in Java Using Lambda Expression

Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String, we just need to iterate over characters again th

3 min read Solve the Logical Expression given by string

Given string str representing a logical expression which consists of the operators | (OR), & (AND),! (NOT) , 0, 1 and, only (i.e. no space between characters). The task is to print the result of the logical expression. Examples: Input: str = "[[0,&,1],|,[!,1]]" Output: 0 Explanation:[[0,&,1],|,[!,1]] [[0,&,1],|,0] [[0,&,1],|,0]

5 min read How to check string is alphanumeric or not using Regular Expression

Given string str, the task is to check whether the string is alphanumeric or not by using Regular Expression. An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Examples: Input: str = "GeeksforGeeks123" Output: true Explanation: This string contains all the alphabets from a-z, A-Z, and the numbe

5 min read

Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)

In Set 1, we have discussed general approach to check whether a string is a valid number or not. In this post, we will discuss regular expression approach to check for a number. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false Check if a given string is

3 min read Find all the patterns of "1(0+)1" in a given string using Regular Expression

In Set 1, we have discussed general approach for counting the patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s.In this post, we will discuss regular expression approach to count the same. Examples: Input : 1101001 Output : 2 Input : 100001abc101 Output : 2 Below is one of the regular expression for above p

3 min read Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)

Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero is present in between 1's. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not. Examples: Input : 100 Output : VALID Input : 1110001 Output : NOT VALID There is 0 between 1s Input :

3 min read Python | Print unique rows in a given boolean matrix using Set with tuples

Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python

2 min read Find regions with most common region size in a given boolean matrix

Given a boolean 2D array, arr[][] of size N*M where a group of connected 1s forms an island. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. The task is to find the position of the top left corner of all the regions with the most common region size. Examples: Input: arr[][] = 12 min read Problem solving on Boolean Model and Vector Space Model

Boolean Model: It is a simple retrieval model based on set theory and boolean algebra. Queries are designed as boolean expressions which have precise semantics. Retrieval strategy is based on binary decision criterion. Boolean model considers that index terms are present or absent in a document. Problem Solving: Consider 5 documents with a vocabula

4 min read A Boolean Array Puzzle

Input: A array arr[] of two elements having value 0 and 1Output: Make both elements 0. Specifications: Following are the specifications to follow. 1) It is guaranteed that one element is 0 but we do not know its position.2) We can't say about another element it can be 0 or 1.3) We can only complement array elements, no other operation like and, or,

4 min read A Boolean Matrix Question

Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1. Examples: Input: <, >Output: <<1, 1>>Input: , >Output: <, > Input: <<1, 0, 0, 1>, , >Output: <<1, 1, 1,

15+ min read Bit Manipulation technique to replace boolean arrays of fixed size less than 64

Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can. Boolean arrays have been

10 min read Boolean Parenthesization Problem | DP-37

Given a boolean expression with the following symbols. Symbols 'T' ---> true 'F' ---> false And following operators filled between symbols Operators & ---> boolean AND | ---> boolean OR ^ ---> boolean XOR Count the number of ways we can parenthesize the expression so that the value of expression evaluates to true. Let the input b