Evaluate a boolean expression represented as string - GeeksforGeeks

15 Mar, 2022
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.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to evaluate value of an expression.#include <bits/stdc++.h> 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        // is AND.        if (s[i + 1] == 'A') {            if (s[i + 2] == '0'|| s[i] == '0')                s[i + 2] = '0';            else                s[i + 2] = '1';        }         // If operator next to current operand        // is OR.        else if (s[i + 1] == 'B') {            if (s[i + 2] == '1'|| s[i] == '1')                s[i + 2] = '1';            else                s[i + 2] = '0';        }         // If operator next to current operand        // is XOR (Assuming a valid input)        else {            if (s[i + 2] == s[i])                s[i + 2] = '0';            else                s[i + 2] = '1';        }    }    return s[n - 1] -'0';} // Driver codeint main(){    string s = "1C1B1B0A0";    cout << evaluateBoolExpr(s);    return 0;}
// 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            // is AND.            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');                    else                        s.setCharAt(i + 2, '1');                }                          // If operator next to current operand                // is OR.                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');                    else                        s.setCharAt(i + 2, '0');                }                                 // If operator next to current operand                // is XOR (Assuming a valid input)                else {                    if (s.charAt(i + 2) == s.charAt(i))                        s.setCharAt(i + 2, '0');                    else                        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 program to evaluate value# of an expression.import math as mt def evaluateBoolExpr(s):     n = len(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"):                s[i + 2] = "0"            else:                s[i + 2] = "1"         # If operator next to current        # operand is OR.        else if (s[i + 1] == "B"):            if (s[i + 2] == "1" or s[i] == "1"):                s[i + 2] = "1"            else:                s[i + 2] = "0"         # If operator next to current operand        # is XOR (Assuming a valid input)        else:            if (s[i + 2] == s[i]):                s[i + 2] = "0"            else:                s[i + 2] = "1"     return ord(s[n - 1]) - ord("0") # Driver codes = "1C1B1B0A0"string=[s[i] for i in range(len(s))]print(evaluateBoolExpr(string)) # This code is contributed# by mohit kumar 29
// C# program to evaluate value// of an expression.using System;using System.Text; class GFG{ // Evaluates boolean expression// and returns the resultpublic 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)                {                    s[i + 2] = '0';                }                else                {                    s[i + 2] = '1';                }            }             // 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')                {                    s[i + 2] = '1';                }                else                {                    s[i + 2] = '0';                }            }             // If operator next to current operand            // is XOR (Assuming a valid input)            else            {                if (s[i + 2] == s[i])                {                    s[i + 2] = '0';                }                else                {                    s[i + 2] = '1';                }            }        }    }    return s[n - 1] - '0';} // Driver codepublic 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        // is AND.        if (($i + 1) < $n  && $s[$i + 1] == 'A')        {            if ($s[$i + 2] == '0'|| $s[$i] == '0')                $s[$i + 2] = '0';            else                $s[$i + 2] = '1';        }         // 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')                $s[$i + 2] = '1';            else                $s[$i + 2] = '0';        }         // If operator next to current operand        // is XOR (Assuming a valid input)        else        {            if (($i + 2) < $n  && $s[$i + 2] == $s[$i])                $s[$i + 2] = '0';            else                $s[$i + 2] = '1';        }    }    return $s[$n - 1] -'0';} // Driver code$s = "1C1B1B0A0";echo evaluateBoolExpr($s); // This code is contributed// by Akanksha Rai
<script> // Javascript program to evaluate// value of an expression. // Evaluates boolean expression// and returns the resultfunction 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' ||                    s[i] == 0)                {                    s[i + 2] = '0';                }                else                {                    s[i + 2] = '1';                }            }             // 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')                {                    s[i + 2] = '1';                }                else                {                    s[i + 2] = '0';                }            }             // If operator next to current operand            // is XOR (Assuming a valid input)            else            {                if (s[i + 2] == s[i])                {                    s[i + 2] = '0';                }                else                {                    s[i + 2] = '1';                }            }        }    }    return (s[n - 1].charCodeAt() -                 '0'.charCodeAt());} // Driver codelet s = "1C1B1B0A0";let sb = s.split(''); document.write(evaluateBoolExpr(sb) + "</br>"); // This code is contributed by rameshtravel07 </script>
Output: 
0
This article is contributed by Ayushi Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
shrikanth13
mohit kumar 29
Akanksha_Rai
rameshtravel07
surinderdawra388
Microsoft
Strings
Microsoft
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Reverse words in a given string
Caesar Cipher in Cryptography
Length of the longest substring without repeating characters
Check whether two strings are anagram of each other