Minimum swaps required to make a binary string divisible by 2 ^ k | Java implementation of the approach ; Function to return the minimum swaps required ; To store the final answer ; To store the count of one and zero ; Loop from end of the string ; If s [ i ] = 1 ; If s [ i ] = 0 ; If c_zero = k ; If the result can 't  be achieved ; Return the final answer ; Driver code
class GFG { static int findMinSwaps ( String s , int k ) { int ans = 0 ; int c_one = 0 , c_zero = 0 ; for ( int i = s . length ( ) - 1 ; i >= 0 ; i -- ) { if ( s . charAt ( i ) == '1' ) c_one ++ ; if ( s . charAt ( i ) == '0' ) { c_zero ++ ; ans += c_one ; } if ( c_zero == k ) break ; } if ( c_zero < k ) return - 1 ; return ans ; } public static void main ( String [ ] args ) { String s = "100111" ; int k = 2 ; System . out . println ( findMinSwaps ( s , k ) ) ; } }