Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if three numbers are equal

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;
}
like image 979
user3316874 Avatar asked Dec 25 '22 12:12

user3316874


1 Answers

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));

}

like image 55
LearningC Avatar answered Feb 07 '23 22:02

LearningC