Number of flips to make binary string alternate | Set 1 | 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
< ? php function flip ( $ ch ) { return ( $ ch == '0' ) ? '1' : '0' ; } function getFlipWithStartingCharcter ( $ str , $ expected ) { $ flipCount = 0 ; for ( $ i = 0 ; $ i < strlen ( $ str ) ; $ i ++ ) { if ( $ str [ $ i ] != $ expected ) $ flipCount ++ ; $ expected = flip ( $ expected ) ; } return $ flipCount ; } function minFlipToMakeStringAlternate ( $ str ) { return min ( getFlipWithStartingCharcter ( $ str , '0' ) , getFlipWithStartingCharcter ( $ str , '1' ) ) ; } $ str = "0001010111" ; echo minFlipToMakeStringAlternate ( $ str ) ; ? >