Find Binary string by converting all 01 or 10 to 11 after M iterations | C ++ program for the above approach . ; Function to find the modified binary string after M iterations ; Set the value of M to the minimum of N or M . ; Declaration of current string state ; Loop over M iterations ; Set the current state as null before each iteration ; Check if this zero has exactly one 1 as neighbour ; Flip the zero ; If there is no change , then no need for further iterations . ; Set the current state as the new previous state ; Driver Code ; Given String ; Number of Iterations ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findString ( string str , int M ) { int N = str . length ( ) ; M = min ( M , N ) ; string s1 = " " ; while ( M != 0 ) { s1 = " " ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == '0' ) { if ( ( str [ i - 1 ] == '1' && str [ i + 1 ] != '1' ) || ( str [ i - 1 ] != '1' && str [ i + 1 ] == '1' ) ) s1 += '1' ; else s1 += '0' ; } else s1 += '1' ; } if ( str == s1 ) break ; str = s1 ; M -- ; } cout << s1 ; } int main ( ) { string str = "0110100" ; int M = 3 ; findString ( str , M ) ; return 0 ; }