There are three integer numbers: a, b, c. Two of them are equal. Need to write a statement result of which is a different number. The statement should not use a comparison operator.
Examples:
input: 2, 2, 4
result: 4
input: 4, 2, 4
result: 2
input: -3, 0, 0
result: -3
CodePudding user response:
Use the xor
operator of your preferred language, usually ^
.
The xor
operator, makes a bitwise or of the corresponding operands where the result for each pair of corresponding bits is set if and only if one of the pairs has that bit set. This results in a 0 for identical numbers, since they have all the exact same bits set. Making an xor
between 0 and any number results in that number since all 1 ^ 0
s and 0 ^ 1
result in a one.
Thus a ^ b ^ c
results in the unique number between the three integers.
As an example let's take a = 3
, b = 3
, and c = 4
. The binary representation of them are as follows:
a = 00000011
b = 00000011
c = 00000100
xor
ing a
and b
results in 0, since the binary representation is identical. And xor
ing c
with 0 results in c
since all the set bits in c
are unset in 0 and there are no bits set in 0 that could potentially pair with an unset bit in c
to give different results.