Minimum flips to make all 1 s in left and 0 s in right | Set 1 ( Using Bitmask ) | Function to count minimum number of flips ; This is converting string s into integer of base 2 ( if s = '100' then num = 4 ) ; Initialize minXor with n that can be maximum number of flips ; Right shift 1 by ( n - 1 ) bits ; Calculate bitwise XOR of num and mask ; Math . min ( a , b ) returns minimum of a and b return minimum number of flips till that digit ; Function to count number of 1 s ; Driver code
def findMiniFlip ( nums ) : NEW_LINE INDENT n = len ( nums ) NEW_LINE s = ' ' NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += str ( nums [ i ] ) NEW_LINE DEDENT num = int ( s , 2 ) NEW_LINE minXor = n ; NEW_LINE mask = ( 1 << ( n - 1 ) ) NEW_LINE while ( n - 1 > 0 ) : NEW_LINE INDENT temp = ( num ^ mask ) NEW_LINE minXor = min ( minXor , countones ( temp ) ) NEW_LINE n -= 1 NEW_LINE mask = ( mask | ( 1 << n - 1 ) ) NEW_LINE DEDENT return minXor NEW_LINE DEDENT def countones ( n ) : NEW_LINE INDENT c = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE c += 1 NEW_LINE DEDENT return c NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT nums = [ 1 , 0 , 1 , 1 , 0 , 0 , 0 ] NEW_LINE n = findMiniFlip ( nums ) NEW_LINE print ( n ) NEW_LINE DEDENT