Saturday, December 30, 2006

To find the greater of two number

Yes, but without using comparison operators!!!!

the first solution came from Mayank... which was:

int max(a,b)
{
if(a/b)
return a;
else return b;
}

The above would not work if b=0... now the second one came from Muneish which was:

x=(a-b)/|a-b|

if(x+|x|)
return a;
else return b;

Now this one is also wrong since a-b could cause overflow...
Well the correct solution goes as follows:

void compare (int a, int b)
{
int diff, msb;

msb = 1 << (sizeof(int)*8 - 1);

if ((a & msb) &amp;& !(b &msb)) /* a is negative and not b */ return b; else if ((b & msb) &amp;amp;amp;amp;amp;& !(a &msb)) /* b is negative and not a */ return a; /* a and b are of same sign */ diff = a-b; if (!diff || !(diff & msb)) /* a==b and a > b */
return a;
return b;
}

I have shamelessly copied this code from Joju John, but was worth the search... A point to be noticed is that msb and diif variables are taken as int but you have to make there types as same as that of a and b.

No comments: