Check if binary string multiple of 3 using DFA | C ++ program to check if the binary string is divisible by 3. ; Function to check if the binary string is divisible by 3. ; checking if the bit is nonzero ; checking if the nonzero bit is at even position ; Checking if the difference of non - zero oddbits and evenbits is divisible by 3. ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CheckDivisibilty ( string A ) { int oddbits = 0 , evenbits = 0 ; for ( int counter = 0 ; counter < A . length ( ) ; counter ++ ) { if ( A [ counter ] == '1' ) { if ( counter % 2 == 0 ) { evenbits ++ ; } else { oddbits ++ ; } } } if ( abs ( oddbits - evenbits ) % 3 == 0 ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } } int main ( ) { string A = "10101" ; CheckDivisibilty ( A ) ; return 0 ; }