Flip all 0 s in given Binary Strings K times with different neighbours | C ++ program for the above approach ; Function to modify the given string K number of times by flipping 0 s having different adjacent characters ; Size of the string ; Stores modified string after each iteration ; Iterate over the range [ 0 k ] ; Traverse the string S ; If '0' is present at 0 th index then replace it with 1 st index ; If '0' is present at the last index then replace it with last index - 1 character ; Otherwise , convert 0 s to 1 if the adjacent characters are different ; If during this iteration there is no change in the string then break this loop ; Update the string S ; Print the updated string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void convertString ( string S , int k ) { int n = S . length ( ) ; string temp = S ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( j == 0 && S [ j ] == '0' ) { temp [ j ] = S [ j + 1 ] ; } else if ( j == n - 1 && S [ j ] == '0' ) { temp [ j ] = S [ j - 1 ] ; } else if ( S [ j - 1 ] != S [ j + 1 ] && S [ j ] == '0' ) { temp [ j ] = '1' ; } } if ( S == temp ) { break ; } S = temp ; } cout << S ; } int main ( ) { string S = "10010001" ; int K = 1 ; convertString ( S , K ) ; return 0 ; }