Minimize bits to be flipped in X and Y such that their Bitwise OR is equal to Z | This function returns minimum number of bits to be flipped in X and Y to make X | Y = Z ; If current bit in Z is set and is also set in either of X or Y or both ; If current bit in Z is set and is unset in both X and Y ; Set that bit in either X or Y ; If current bit in Z is unset and is set in both X and Y ; Unset the bit in both X and Y ; If current bit in Z is unset and is set in either X or Y ; Unset that set bit ; Driver Code
def minimumFlips ( X , Y , Z ) : NEW_LINE INDENT res = 0 NEW_LINE while ( X > 0 or Y > 0 or Z > 0 ) : NEW_LINE INDENT if ( ( ( X & 1 ) or ( Y & 1 ) ) and ( Z & 1 ) ) : NEW_LINE INDENT X = X >> 1 NEW_LINE Y = Y >> 1 NEW_LINE Z = Z >> 1 NEW_LINE continue NEW_LINE DEDENT elif ( not ( X & 1 ) and not ( Y & 1 ) and ( Z & 1 ) ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT elif ( ( X & 1 ) or ( Y & 1 ) == 1 ) : NEW_LINE INDENT if ( ( X & 1 ) and ( Y & 1 ) and not ( Z & 1 ) ) : NEW_LINE INDENT res += 2 NEW_LINE DEDENT elif ( ( ( X & 1 ) or ( Y & 1 ) ) and not ( Z & 1 ) ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT X = X >> 1 NEW_LINE Y = Y >> 1 NEW_LINE Z = Z >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 5 NEW_LINE Y = 8 NEW_LINE Z = 6 NEW_LINE print ( minimumFlips ( X , Y , Z ) ) NEW_LINE DEDENT