How to determine if three numbers are equal

Using strictly bitwise operations, how to determine if the three numbers are equal. So far, I have the code shown below, but it does not 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;
}
+4
source share
4 answers

try it

int check(int a,int b,int c)
{
    return !((a^b)|(b^c));
}

Since there are no restrictions on the number of operators used, if! not allowed, then this can also be a solution, given 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));

}

+4
source

Based on @Rohith's answer

int check(int a,int b,int c)
{
    return !((a^b)|(b^c));
}

(please support him if you reproach mine)

if you do not want !:

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 think, is a little easier than him.

+3
int isEqualThree(int x, int y, int z) {
    int a=(x^y);
    int b=(y^z);

    return !(a|b);

}

xorof two numbers are equal to zero only when all bits of the numbers are identical. So, from above, if either aor bis nonzero, this means that at least one number is different from the other two. So, in this case, return another zero, which explains return !(a|b);.

+1
source

If == is valid there also

int check (int x, int y, int z) {return (x | y | z) == (x and y and z); }

0
source

Source: https://habr.com/ru/post/1530053/


All Articles