Minimum Count of Bit flips required to make a Binary String Palindromic | Function to calculate the length of the binary string ; Length ; Right shift of n ; Increment the length ; Return the length ; Function to check if the bit present at i - th position is a set bit or not ; Returns true if the bit is set ; Function to count the minimum number of bit flips required ; Length of the binary form ; Number of flips ; Pointer to the LSB ; Pointer to the MSB ; Check if the bits are equal ; Decrementing the left pointer ; Incrementing the right pointer ; Returns the number of bits to flip . ; Driver Code
def check_length ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n >> 1 NEW_LINE ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def check_ith_bit ( n , i ) : NEW_LINE INDENT if ( n & ( 1 << ( i - 1 ) ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def no_of_flips ( n ) : NEW_LINE INDENT ln = check_length ( n ) NEW_LINE ans = 0 NEW_LINE right = 1 NEW_LINE left = ln NEW_LINE while ( right < left ) : NEW_LINE INDENT if ( check_ith_bit ( n , right ) != check_ith_bit ( n , left ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT left -= 1 NEW_LINE right += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 12 NEW_LINE print ( no_of_flips ( n ) ) NEW_LINE