text: Minimum given operations required to convert a given binary string to all 1 's | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int changeToOnes ( string str ) { int i , l , ctr = 0 ; l = str . length ( ) ; for ( i = l - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '1' ) ctr ++ ; else break ; } return l - ctr ; } string removeZeroesFromFront ( string str ) { string s ; int i = 0 ; while ( i < str . length ( ) && str [ i ] == '0' ) i ++ ; if ( i == str . length ( ) ) s = "0" ; else s = str . substr ( i , str . length ( ) - i ) ; return s ; } int main ( ) { string str = "10010111" ; str = removeZeroesFromFront ( str ) ; cout << changeToOnes ( str ) ; return 0 ; }