Choose X such that ( A xor X ) + ( B xor X ) is minimized | Function to return the integer X such that ( A xor X ) + ( B ^ X ) is minimized ; While either A or B is non - zero ; Position at which both A and B have a set bit ; Inserting a set bit in x ; Right shifting both numbers to traverse all the bits ; Driver code
def findX ( A , B ) : NEW_LINE INDENT j = 0 NEW_LINE x = 0 NEW_LINE while ( A or B ) : NEW_LINE INDENT if ( ( A & 1 ) and ( B & 1 ) ) : NEW_LINE INDENT x += ( 1 << j ) NEW_LINE DEDENT A >>= 1 NEW_LINE B >>= 1 NEW_LINE j += 1 NEW_LINE DEDENT return x NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 2 NEW_LINE B = 3 NEW_LINE X = findX ( A , B ) NEW_LINE print ( " X ▁ = " , X , " , ▁ Sum ▁ = " , ( A ^ X ) + ( B ^ X ) ) NEW_LINE DEDENT