Related Articles

Related Articles

Check if binary string multiple of 3 using DFA
  • Difficulty Level : Easy
  • Last Updated : 26 Oct, 2020

Given a string of binary characters, check if it is multiple of 3 or not.
Examples : 

Input :  1 0 1 0
Output : NO
Explanation : (1 0 1 0) is 10 and hence
not a multiple of 3

Input :  1 1 0 0
Output : YES
Explanation : (1 1 0 0) is 12 and hence 
a multiple of 3

Approach : One simple method is to convert the binary number into its decimal representation and then check if it is a multiple of 3 or not. Now, when it comes to DFA (Deterministic Finite Automata), there is no concept of memory i.e. you cannot store the string when it is provided, so the above method would not be applicable. In simple terms, a DFA takes a string as input and process it. If it reaches final state, it is accepted, else rejected. As you cannot store the string, so input is taken character by character.

The DFA for given problem is : 

As, when a number is divided by 3, there are only 3 possibilities. The remainder can be either 0, 1 or 2. Here, state 0 represents that the remainder when the number is divided by 3 is 0. State 1 represents that the remainder when the number is divided by 3 is 1 and similarly state 2 represents that the remainder when the number is divided by 3 is 2. So if a string reaches state 0 in the end, it is accepted otherwise rejected.



Below is the implementation of above approach : 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to illustrate
// DFA for multiple of 3
#include <bits/stdc++.h>
using namespace std;
 
// checks if binary characters
// are multiple of 3
bool isMultiple3(char c[], int size)
{
    // initial state is 0th
    char state = '0';
 
    for (int i = 0; i < size; i++) {
 
        // storing binary digit
        char digit = c[i];
 
        switch (state) {
 
        // when state is 0
        case '0':
            if (digit == '1')
                state = '1';
            break;
 
        // when state is 1
        case '1':
            if (digit == '0')
                state = '2';
            else
                state = '0';
            break;
 
        // when state is 2
        case '2':
            if (digit == '0')
                state = '1';
            break;
        }
    }
 
    // if final state is 0th state
    if (state == '0')
        return true;
    return false;
}
 
// Driver's Code
int main()
{
    // size of binary array
    int size = 5;
 
    // array of binary numbers
    // Here it is 21 in decimal
    char c[] = { '1', '0', '1', '0', '1' };
 
    // if binary numbers are a multiple of 3
    if (isMultiple3(c, size))
        cout << "YES\n";
    else
        cout << "NO\n";
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to illustrate
// DFA for multiple of 3
import java.io.*;
 
class GFG
{
    // checks if binary characters
    // are multiple of 3
    static boolean isMultiple3(char c[], int size)
    {
        // initial state is 0th
        char state = '0';
     
        for (int i = 0; i < size; i++) {
     
            // storing binary digit
            char digit = c[i];
     
            switch (state) {
     
            // when state is 0
            case '0':
                if (digit == '1')
                    state = '1';
                break;
     
            // when state is 1
            case '1':
                if (digit == '0')
                    state = '2';
                else
                    state = '0';
                break;
     
            // when state is 2
            case '2':
                if (digit == '0')
                    state = '1';
                break;
            }
        }
     
        // if final state is 0th state
        if (state == '0')
            return true;
        return false;
    }
     
 
 
 
    // Driver Code
    public static void main (String[] args)
    {
        // size of binary array
        int size = 5;
     
        // array of binary numbers
        // Here it is 21 in decimal
        char c[] = { '1', '0', '1', '0', '1' };
     
        // if binary numbers are a multiple of 3
        if (isMultiple3(c, size))
            System.out.println ("YES");
        else
            System.out.println ("NO");
             
    }
}
// This code is contributed by vt_m

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to illustrate
# DFA for multiple of 3
 
# Checks if binary characters
# are multiple of 3
def isMultiple3(c, size):
     
    # Initial state is 0th
    state = '0'
     
    for i in range(size):
         
        # Storing binary digit
        digit = c[i]
         
        # When state is 0
        if state == '0':
            if (digit == '1'):
                state = '1'
         
        # When state is 1        
        elif state == '1':
            if (digit == '0'):
                state = '2'
            else:
                state = '0'
         
        # When state is 2        
        elif state == '2':
            if (digit == '0'):
                state = '1'
   
    # If final state is 0th state
    if (state == '0'):
        return True
         
    return False
 
# Driver code
if __name__=="__main__":
     
    # Size of binary array
    size = 5;
  
    # Array of binary numbers
    # Here it is 21 in decimal
    c = [ '1', '0', '1', '0', '1']
  
    # If binary numbers are a multiple of 3
    if (isMultiple3(c, size)):
        print("YES")
    else:
        print("NO")
 
# This code is contributed by rutvik_56

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate
// DFA for multiple of 3
using System;
 
class GFG {
     
    // checks if binary characters
    // are multiple of 3
    static bool isMultiple3(char []c, int size)
    {
        // initial state is 0th
        char state = '0';
     
        for (int i = 0; i < size; i++)
        {
     
            // storing binary digit
            char digit = c[i];
     
            switch (state)
            {
     
                // when state is 0
                case '0':
                    if (digit == '1')
                        state = '1';
                    break;
         
                // when state is 1
                case '1':
                    if (digit == '0')
                        state = '2';
                    else
                        state = '0';
                    break;
         
                // when state is 2
                case '2':
                    if (digit == '0')
                        state = '1';
                    break;
            }
        }
     
        // if final state is 0th state
        if (state == '0')
            return true;
             
        return false;
    }
 
    // Driver Code
    public static void Main ()
    {
         
        // size of binary array
        int size = 5;
     
        // array of binary numbers
        // Here it is 21 in decimal
        char []c = { '1', '0', '1', '0', '1' };
     
        // if binary numbers are a multiple of 3
        if (isMultiple3(c, size))
            Console.WriteLine ("YES");
        else
            Console.WriteLine ("NO");
    }
}
 
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to illustrate
// DFA for multiple of 3
 
// checks if binary characters
// are multiple of 3
function isMultiple3($c,$size)
{
     
    // initial state is 0th
    $state = '0';
 
    for ($i = 0; $i < $size; $i++)
    {
 
        // storing binary digit
        $digit = $c[$i];
 
        switch ($state)
        {
 
            // when state is 0
            case '0':
                if ($digit == '1')
                    $state = '1';
                break;
     
            // when state is 1
            case '1':
                if ($digit == '0')
                    $state = '2';
                else
                    $state = '0';
                break;
     
            // when state is 2
            case '2':
                if ($digit == '0')
                    $state = '1';
                break;
        }
    }
 
    // if final state is 0th state
    if ($state == '0')
        return true;
    return false;
}
 
    // Driver Code
 
    // size of binary array
    $size = 5;
 
    // array of binary numbers
    // Here it is 21 in decimal
    $c= array('1', '0', '1', '0', '1');
 
    // if binary numbers are
    // a multiple of 3
    if (isMultiple3($c, $size))
        echo "YES\n";
    else
        echo "NO\n";
 
//This code is contributed by mits
?>

chevron_right


Output: 

YES


 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :