Check if binary string multiple of 3 using DFA
Last Updated :
15 Jun, 2022
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 1 : 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++
// 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;
}
Java
// 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
Python3
# Python program to check if the binary String is divisible
# by 3.
# Function to check if the binary String is divisible by 3.
def CheckDivisibilty(A):
oddbits = 0;
evenbits = 0;
for counter in range(len(A)):
# checking if the bit is nonzero
if (A[counter] == '1'):
# checking if the nonzero bit is at even
# position
if (counter % 2 == 0):
evenbits+=1;
else:
oddbits+=1;
# Checking if the difference of non-zero oddbits and
# evenbits is divisible by 3.
if (abs(oddbits - evenbits) % 3 == 0):
print("Yes" + "");
else:
print("No" + "");
# Driver Program
if __name__ == '__main__':
A = "10101";
CheckDivisibilty(A);
# This code contributed by umadevi9616 Added code in Python
C#
// 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.
PHP
<?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
?>
JavaScript
<script>
// JavaScript Program to illustrate
// DFA for multiple of 3
// checks if binary characters
// are multiple of 3
function isMultiple3(c, size)
{
// initial state is 0th
let state = '0';
for (let i = 0; i < size; i++) {
// storing binary digit
let 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
let size = 5;
// array of binary numbers
// Here it is 21 in decimal
let c = [ '1', '0', '1', '0', '1' ];
// if binary numbers are a multiple of 3
if (isMultiple3(c, size))
document.write ("YES");
else
document.write ("NO");
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 2:We will check if the difference between the number of non-zero odd bit positions and non-zero even bit positions is divisible by 3 or not.
Mathematically -> |odds-evens| divisible by 3.
Code:
C++
// C++ program to check if the binary string is divisible
// by 3.
#include <bits/stdc++.h>
using namespace std;
// Function to check if the binary string is divisible by 3.
void CheckDivisibilty(string A)
{
int oddbits = 0, evenbits = 0;
for (int counter = 0; counter < A.length(); counter++) {
// checking if the bit is nonzero
if (A[counter] == '1') {
// checking if the nonzero bit is at even
// position
if (counter % 2 == 0) {
evenbits++;
}
else {
oddbits++;
}
}
}
// Checking if the difference of non-zero oddbits and
// evenbits is divisible by 3.
if (abs(oddbits - evenbits) % 3 == 0) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
// Driver Program
int main()
{
string A = "10101";
CheckDivisibilty(A);
return 0;
}
Java
// Java program to check if the binary String is divisible
// by 3.
import java.util.*;
class GFG
{
// Function to check if the binary String is divisible by 3.
static void CheckDivisibilty(String A)
{
int oddbits = 0, evenbits = 0;
for (int counter = 0; counter < A.length(); counter++)
{
// checking if the bit is nonzero
if (A.charAt(counter) == '1')
{
// checking if the nonzero bit is at even
// position
if (counter % 2 == 0) {
evenbits++;
}
else {
oddbits++;
}
}
}
// Checking if the difference of non-zero oddbits and
// evenbits is divisible by 3.
if (Math.abs(oddbits - evenbits) % 3 == 0) {
System.out.print("Yes" +"\n");
}
else {
System.out.print("No" +"\n");
}
}
// Driver Program
public static void main(String[] args)
{
String A = "10101";
CheckDivisibilty(A);
}
}
// This code is contributed by umadevi9616
Python3
# Python program to check if the binary String is divisible
# by 3.
# Function to check if the binary String is divisible by 3.
def CheckDivisibilty(A):
oddbits = 0;
evenbits = 0;
for counter in range(len(A)):
# checking if the bit is nonzero
if (A[counter] == '1'):
# checking if the nonzero bit is at even
# position
if (counter % 2 == 0):
evenbits += 1;
else:
oddbits += 1;
# Checking if the difference of non-zero oddbits and
# evenbits is divisible by 3.
if (abs(oddbits - evenbits) % 3 == 0):
print("Yes" + "");
else:
print("No" + "");
# Driver Program
if __name__ == '__main__':
A = "10101";
CheckDivisibilty(A);
# This code is contributed by umadevi9616.
C#
// C# program to check if the binary String is divisible
// by 3.
using System;
public class GFG
{
// Function to check if the binary String is divisible by 3.
static void CheckDivisibilty(String A)
{
int oddbits = 0, evenbits = 0;
for (int counter = 0; counter < A.Length; counter++)
{
// checking if the bit is nonzero
if (A[counter] == '1')
{
// checking if the nonzero bit is at even
// position
if (counter % 2 == 0) {
evenbits++;
}
else {
oddbits++;
}
}
}
// Checking if the difference of non-zero oddbits and
// evenbits is divisible by 3.
if (Math.Abs(oddbits - evenbits) % 3 == 0) {
Console.Write("Yes" +"\n");
}
else {
Console.Write("No" +"\n");
}
}
// Driver Program
public static void Main(String[] args)
{
String A = "10101";
CheckDivisibilty(A);
}
}
// This code is contributed by umadevi9616
JavaScript
<script>
// javascript program to check if the binary String is divisible
// by 3.
// Function to check if the binary String is divisible by 3.
function CheckDivisibilty( A) {
var oddbits = 0, evenbits = 0;
for (var counter = 0; counter < A.length; counter++) {
// checking if the bit is nonzero
if (A[counter] == '1') {
// checking if the nonzero bit is at even
// position
if (counter % 2 == 0) {
evenbits++;
} else {
oddbits++;
}
}
}
// Checking if the difference of non-zero oddbits and
// evenbits is divisible by 3.
if (Math.abs(oddbits - evenbits) % 3 == 0) {
document.write("Yes" + "\n");
} else {
document.write("No" + "\n");
}
}
// Driver Program
var A = "10101";
CheckDivisibilty(A);
// This code is contributed by umadevi9616
</script>
Time Complexity: O(n) where n is the number of bits.
Auxiliary Space: O(1)
Similar Reads
Check for Binary String
Given a string s, the task is to check if it is a binary string or not. A binary string is a string which only contains the characters '0' and '1'.Examples:Input: s = "01010101010"Output: trueInput: s = "geeks101"Output: false Approach:The idea is to iterate over all the characters of the string and
3 min read
Check if an encoding represents a unique binary string
Given an encoding of a binary string of length k, the task is to find if the given encoding uniquely identifies a binary string or not. The encoding has counts of contiguous 1s (separated by 0s). For example, encoding of 11111 is {5}, encoding of 01101010 is {2, 1, 1} and encoding of 111011 is {3, 2
6 min read
Check If it is Possible to Convert Binary String into Unary String
Given a binary string S of length N. You can apply following operation on S any number of times. Choose two adjacent characters, such that both are 1's or 0's. Then invert them, Formally, if both are 0's then into 1's or vice-versa. Then your task is to output YES or NO, by checking that using given
6 min read
Check if a binary string contains all permutations of length k
Given a binary string and k, to check whether it's contains all permutations of length k or not. Examples: Input : Binary string 11001 k : 2 Output : Yes 11001 contains all possibilities of binary sequences with k = 2, 00, 01, 10, 11 Input : Binary string: 1001 k : 2 Output: No 1001 does not contain
13 min read
Check if a string is made up of K alternating characters
Given a string str and an integer K, the task is to check if it is made up of K alternating characters. Examples: Input: str = "acdeac", K = 4 Output: Yes Input: str = "abcdcab", K = 2 Output: No Approach: In order for the string to be made up of K alternating characters, it must satisfy the followi
5 min read
Check if decimal representation of Binary String is divisible by 9 or not
Given a binary string S of length N, the task is to check if the decimal representation of the binary string is divisible by 9 or not. Examples: Input: S = 1010001Output:YesExplanation: The decimal representation of the binary string S is 81, which is divisible by 9. Therefore, the required output i
12 min read
Check if all substrings of length K of a Binary String has equal count of 0s and 1s
Given a binary string S of length N and an even integer K, the task is to check if all substrings of length K contains an equal number of 0s and 1s. If found to be true, print âYesâ. Otherwise, print âNoâ. Examples: Input: S = "101010", K = 2Output: YesExplanation:Since all the substrings of length
6 min read
Check if given Binary string follows then given condition or not
Given binary string str, the task is to check whether the given string follows the below condition or not: String starts with a '1'.Each '1' is followed by empty string(""), '1', or "00".Each "00" is followed by empty string(""), '1'. If the given string follows the above criteria then print "Valid
10 min read
Find the minimum number of distinct Substrings formed by 0s in Binary String
Given two integers N and M, the task is to output the minimum number of different substrings that can be formed using the Binary String of length N having M number of set bits. Note: Two substrings let say S[x, y] and S[a, b] are different. If either x != a or y != b. Examples: Input: N = 3, M = 1Ou
6 min read
Check if a string follows a^nb^n pattern or not
Given string str, return true string follows pattern anbn, i.e., it has a's followed by b's such that the number of a's and b's are same. Examples: Input : str = "aabb" Output : Yes Input : str = "abab" Output : No Input : str = "aabbb" Output : No The idea is to first count a's. If number of a's is
8 min read