James Fang wrote, On 08/12/07 04:23:
On Dec 7, 1:33 pm, (e-mail address removed) wrote:
Hi all,
The following question is asked frequently in interviews
How to find the greatest of 2 numbers without using relational
operators ?
the solution i have seen is
( a+b + abs(a-b) ) /2 ;
is there any better solution than this ....?????
In your solution there's an overflow issue.
Actually there's a simpler solution: you can use an array, and use the
array index istead of the relational operators.
int max(int a,int b)
{
int array[2];
array[0]=a;
array[1]=b;
return array[(a-b)&0x80000000];
}
Did you actually test this piece of rubbish? When I try it I always get
the value of a. I'm really not sure how it is giving me that since the
code is so broken. Just to show you how bad I've added a bit of
diagnostic and here it is...
markg@brenda:~$ cat t.c
#include<stdio.h>
int max(int a,int b)
{
int array[2];
array[0]=a;
array[1]=b;
printf("%d\n",(a-b)&0x80000000);
return array[(a-b)&0x80000000];
}
int main(void)
{
printf("%d\n",max(1,2));
return 0;}
markg@brenda:~$ gcc -ansi -Wall -Wextra -O t.c
markg@brenda:~$ ./a.out
-2147483648
1
markg@brenda:~$
Obviously the index is just a little outside the array.
C does not have a system stack. Your implementation might, but equally
well it might not work as you expect.
Or they are passed in registers (if you take the address then obviously
it has to allocate a memory location), or the stack might not grow in
the direction you expect, or the parameters might be pushed left to right....
int might not be 32 bits. It invokes undefined behaviour if you take a
pointer to a, add 1 to it, and dereference it.
Sorry, I've made a mistake, the second implementation should be:
int max(int a,int b)
{
// in C standard, the function parameters are pushed from right to
left.
// so integer b is stored in high address.
return *(&a+((a-b)&0x80000000>>31));
}
No, the second implementation should be erased not corrected, and anyone
who thinks it is valid needs to learn C. The first could be corrected as
an intellectual exercise, but should never be used in real life.