Check if binary representations of 0 to N are present as substrings in given binary string | Java program for the above approach ; Function to convert decimal to binary representation ; Iterate over all bits of N ; If bit is 1 ; Return binary representation ; Function to check if binary conversion of numbers from N to 1 exists in the String as a subString or not ; To store the count of number exists as a subString ; Traverse from N to 1 ; If current number is not present in map ; Store current number ; Find binary of t ; If the String s is a subString of str ; Mark t as true ; Increment the count ; Update for t / 2 ; Special judgment '0' ; If the count is N + 1 , return " yes " ; Driver Code ; Given String ; Given number ; Function call
import java . util . * ; class GFG { static String decimalToBinary ( int N ) { String ans = " " ; while ( N > 0 ) { if ( N % 2 == 1 ) { ans = '1' + ans ; } else { ans = '0' + ans ; } N /= 2 ; } return ans ; } static String checkBinaryString ( String str , int N ) { int [ ] map = new int [ N + 10 ] ; int cnt = 0 ; for ( int i = N ; i > 0 ; i -- ) { if ( map [ i ] == 0 ) { int t = i ; String s = decimalToBinary ( t ) ; if ( str . contains ( s ) ) { while ( t > 0 && map [ t ] == 0 ) { map [ t ] = 1 ; cnt ++ ; t >>= 1 ; } } } } for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == '0' ) { cnt ++ ; break ; } } if ( cnt == N + 1 ) return " True " ; else return " False " ; } public static void main ( String [ ] args ) { String str = "0110" ; int N = 3 ; System . out . print ( checkBinaryString ( str , N ) ) ; } }