Number of flips to make binary string alternate | Set 1 | C / C ++ program to find minimum number of flip to make binary string alternate ; Utility method to flip a character ; Utility method to get minimum flips when alternate string starts with expected char ; if current character is not expected , increase flip count ; flip expected character each time ; method return minimum flip to make binary string alternate ; return minimum of following two 1 ) flips when alternate string starts with 0 2 ) flips when alternate string starts with 1 ; Driver code to test above method
#include <bits/stdc++.h> NEW_LINE using namespace std ; char flip ( char ch ) { return ( ch == '0' ) ? '1' : '0' ; } int getFlipWithStartingCharcter ( string str , char expected ) { int flipCount = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] != expected ) flipCount ++ ; expected = flip ( expected ) ; } return flipCount ; } int minFlipToMakeStringAlternate ( string str ) { return min ( getFlipWithStartingCharcter ( str , '0' ) , getFlipWithStartingCharcter ( str , '1' ) ) ; } int main ( ) { string str = "0001010111" ; cout << minFlipToMakeStringAlternate ( str ) ; return 0 ; }