Reputation: 223
Using strictly bitwise operations, how would I determine if three numbers are equal. So far, I have the code shown below, but it doesn't work for edge cases like 0x80000000,0x7fffffff,0x7fffffff.
int isEqualThree(int x, int y, int z) {
int first = x ^ y;
int second = first ^ z;
int third = second ^ x;
int final = !third;
return final;
}
Upvotes: 4
Views: 5670
Reputation: 25169
Building on @LearningC's answer of
int check(int a,int b,int c)
{
return !((a^b)|(b^c));
}
If you don't want the !
:
int check(int a,int b,int c)
{
unsigned int d = (unsigned int) ((a^b)|(b^c)); /* 0 if equal, non-zero otherwise */
d |= d>>32; /* set bit n if bit n+32 set - only needed for 64 bit int platforms */
d |= d>>16; /* set bit n if bit n+16 set */
d |= d>>8; /* set bit n if bit n+8 set */
d |= d>>4; /* set bit n if bit n+4 set */
d |= d>>2; /* set bit n if bit n+2 set */
d |= d>>1; /* set bit n if bit n+1 set */
return (int)((~d) &1);
}
which I believe is a little simpler than his.
Upvotes: 4
Reputation: 284
If == is acceptable, there's also
int check( int x, int y, int z ) { return (x | y | z) == (x & y & z); }
Upvotes: 0
Reputation: 5369
int isEqualThree(int x, int y, int z) {
int a=(x^y);
int b=(y^z);
return !(a|b);
}
xor
of two numbers are zero only when all the bits of the numbers are identical. So from above, if either a
or b
is non-zero then it implies that at least one number is different from the other two. So in that case return zero else one, which explains return !(a|b);
.
Upvotes: 1
Reputation: 3162
try this
int check(int a,int b,int c)
{
return !((a^b)|(b^c));
}
Since there is no constraint specified on number of operators to be used, if ! is not allowed then this can be a solution too considering 32 bit numbers,using only bitwise operators
int check(int a,int b,int c)
{
int d;
d=(a^b)|(b^c);
d=~d;
return ((d>>31&1)&(d>>30&1)&(d>>29&1)&(d>>28&1)&(d>>27&1)&(d>>26&1)&(d>>25&1)&(d>>24&1)&(d>>23&1)&(d>>22&1)&(d>>21&1)&(d>>20&1)&(d>>19&1)&(d>>18&1)&(d>>17&1)&(d>>16&1)&(d>>15&1)&(d>>14&1)&(d>>13&1)&(d>>12&1)&(d>>11&1)&(d>>10&1)&(d>>9&1)&(d>>8&1)&(d>>7&1)&(d>>6&1)&(d>>5&1)&(d>>4&1)&(d>>3&1)&(d>>2&1)&(d>>1&1)&(d&1));
}
Upvotes: 5