Minimum number of replacements to make the binary string alternating | Set 2 | C ++ implementation of the approach ; Function to return the minimum number of characters of the given binary string to be replaced to make the string alternating ; If there is 1 at even index positions ; If there is 0 at odd index positions ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minReplacement ( string s , int len ) { int ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( i % 2 == 0 && s [ i ] == '1' ) ans ++ ; if ( i % 2 == 1 && s [ i ] == '0' ) ans ++ ; } return min ( ans , len - ans ) ; } int main ( ) { string s = "1100" ; int len = s . size ( ) ; cout << minReplacement ( s , len ) ; return 0 ; }