Minimum given operations required to convert a given binary string to all 1 's | Java implementation of the approach ; Function to return the number of operations required ; ctr will store the number of consecutive ones at the end of the given binary string ; Loop to find number of 1 s at the end of the string ; If the current character is 1 ; If we encounter the first 0 from the LSB position then we 'll break the loop ; Number of operations required is ( l - ctr ) ; Function to remove leading zeroes from the string ; Loop until s [ i ] becomes not equal to 1 ; If we reach the end of the string , it means that string contains only 0 's ; Return the string without leading zeros ; Driver code ; Removing the leading zeroes
class GFG { static int changeToOnes ( String str ) { int i , l , ctr = 0 ; l = str . length ( ) ; for ( i = l - 1 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) == '1' ) ctr ++ ; else break ; } return l - ctr ; } static String removeZeroesFromFront ( String str ) { String s ; int i = 0 ; while ( i < str . length ( ) && str . charAt ( i ) == '0' ) i ++ ; if ( i == str . length ( ) ) s = "0" ; else s = str . substring ( i , str . length ( ) - i ) ; return s ; } public static void main ( String [ ] args ) { String str = "10010111" ; str = removeZeroesFromFront ( str ) ; System . out . println ( changeToOnes ( str ) ) ; } }