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: 2
Explanation: Realizing the expression requires 1 AND gate represented by ‘.’ and 1 OR gate represented by ‘+’.
Input: S = “(1 – A). B+C”
Output: 3
Explanation: Realizing the expression requires 1 AND gate represented by ‘.’ and 1 OR gate represented by ‘+’ and 1 NOT gate represented by ‘-‘.
Approach: Follow the steps below to solve the problem:
- Iterate over the characters of the string.
- Initialize, count of gates to 0.
- If the current character is either ‘.’ or ‘+’, or ‘1’, then increment the count of gates by 1
- Print the count of gates required.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void numberOfGates(string s)
{
int N = s.size();
int ans = 0;
for ( int i = 0; i < ( int )s.size(); i++) {
if (s[i] == '.' || s[i] == '+'
|| s[i] == '1' ) {
ans++;
}
}
cout << ans;
}
int main()
{
string S = "(1-A).B+C" ;
numberOfGates(S);
}
|
Java
class GFG{
static void numberOfGates(String s)
{
int N = s.length();
int ans = 0 ;
for ( int i = 0 ; i < ( int )s.length(); i++)
{
if (s.charAt(i) == '.' ||
s.charAt(i) == '+' ||
s.charAt(i) == '1' )
{
ans++;
}
}
System.out.println(ans);
}
public static void main(String[] args)
{
String S = "(1-A).B+C" ;
numberOfGates(S);
}
}
|
Python3
def numberOfGates(s):
N = len (s)
ans = 0
for i in range ( len (s)):
if (s[i] = = '.' or s[i] = = '+' or
s[i] = = '1' ):
ans + = 1
print (ans, end = "")
if __name__ = = "__main__" :
S = "(1-A).B+C"
numberOfGates(S)
|
C#
using System;
public class GFG
{
static void numberOfGates( string s)
{
int N = s.Length;
int ans = 0;
for ( int i = 0; i < s.Length; i++)
{
if (s[i] == '.' ||
s[i] == '+' ||
s[i] == '1' )
{
ans++;
}
}
Console.WriteLine(ans);
}
public static void Main( string [] args)
{
string S = "(1-A).B+C" ;
numberOfGates(S);
}
}
|
Javascript
<script>
function numberOfGates(s)
{
let N = s.length;
let ans = 0;
for (let i = 0; i < s.length; i++)
{
if (s[i] == '.' ||
s[i] == '+' ||
s[i] == '1' )
{
ans++;
}
}
document.write(ans);
}
let S = "(1-A).B+C" ;
numberOfGates(S);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
13 Sep, 2021
Like Article
Save Article