text: Check if decimal representation of Binary String is divisible by 9 or not | C ++ program to implement the above approach ; Function to convert the binary string into octal representation ; Stores binary representation of the decimal value [ 0 - 7 ] ; Stores the decimal values of binary strings [ 0 - 7 ] ; Stores length of S ; Update S ; Update S ; Update N ; Stores octal representation of the binary string ; Traverse the binary string ; Stores 3 consecutive characters of the binary string ; Append octal representation of temp ; Function to check if binary string is divisible by 9 or not ; Stores octal representation of S ; Stores sum of elements present at odd positions of oct ; Stores sum of elements present at odd positions of oct ; Stores length of oct ; Traverse the string oct ; Update oddSum ; Traverse the string oct ; Update evenSum ; Stores cotal representation of 9 ; If absolute value of ( oddSum - evenSum ) is divisible by Oct_9 ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; string ConvertequivalentBase8 ( string S ) { map < string , char > mp ; mp [ "000" ] = '0' ; mp [ "001" ] = '1' ; mp [ "010" ] = '2' ; mp [ "011" ] = '3' ; mp [ "100" ] = '4' ; mp [ "101" ] = '5' ; mp [ "110" ] = '6' ; mp [ "111" ] = '7' ; int N = S . length ( ) ; if ( N % 3 == 2 ) { S = "0" + S ; } else if ( N % 3 == 1 ) { S = "00" + S ; } N = S . length ( ) ; string oct ; for ( int i = 0 ; i < N ; i += 3 ) { string temp = S . substr ( i , 3 ) ; oct . push_back ( mp [ temp ] ) ; } return oct ; } string binString_div_9 ( string S , int N ) { string oct ; oct = ConvertequivalentBase8 ( S ) ; int oddSum = 0 ; int evenSum = 0 ; int M = oct . length ( ) ; for ( int i = 0 ; i < M ; i += 2 ) { oddSum += int ( oct [ i ] - '0' ) ; } for ( int i = 1 ; i < M ; i += 2 ) { evenSum += int ( oct [ i ] - '0' ) ; } int Oct_9 = 11 ; if ( abs ( oddSum - evenSum ) % Oct_9 == 0 ) { return " Yes " ; } return " No " ; } int main ( ) { string S = "1010001" ; int N = S . length ( ) ; cout << binString_div_9 ( S , N ) ; }