NVIDIA Interview Question
Software Engineer / DevelopersThis is the best solution, just wanted to add one more information.
I guess in some machines, while shifting the bits the sign is also saved. So it should be made unsigned int to make the code work in all machines.
So the working code what I have.
int a,b=0;
a = 7;
b = 9;
int diff = (unsigned int)(a-b) >> 31;
printf("\nDiff : %d\n",diff);
int sum = (1-diff)*a + (diff*b);
printf("\n Max of %d and %d is : %d\n",a,b,sum);
It's only one line code if we can use ternary operator.
maxint(int a, int b){
return (a-b >> (sizeof(int)*8 - 1)) ? b:a
}
I also thought of this one, but I think that there might be a problem with it -- we don't know whether abs() uses a conditional in its implementation...
my fault.. i used '<' in for loop:
correcting it:
int a=x=100;
int b=y=500;
int sum=x+y=600;
int max;
int flag1=0,flag2=0,flag3=0;
while(!flag3)
{
a--;
b--;
x++;
y++;
while(!a)
{
flag1=1;
break;
}
while(!b)
{
flag2=1;
break;
}
while(flag1 && flag2)
{
flag3=1;
break;
}
}
max = (x+y-(sum))/2;
cout<<max;
ex:
100 , 500
max = (x+y-(sum))/2;
max=(600+1000-(100+500))/2
max=(1600-(600))/2
max=(1000)/2
max=500
Hmm... its basically how a multiplexer works . suppose 2 numbers are A and B .
- marly April 14, 2007Perform the operation A-B and extract the MSB .let it be k. Now if k =1 then A>B else B>A (2's complement)..
return (1-k)*A+k*B. This will alyways return the maximum of A&B