Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview qns...Do the below without any conditional or comparison operator

Tags:

algorithm

math

Do the below without any conditional or comparison operator.

if (Number <= 0)
{
    Print '0';
}
else
{
    print Number;
}

thanks..

like image 291
nbojja Avatar asked Nov 28 '22 12:11

nbojja


1 Answers

My original simple solution:

1. print( (abs(Number)+Number) / 2 )

That solution would work in most cases, unless Number is very large (more than half the maximum e.g. Number >= MAX_INT/2) in which case the addition may cause overflow.

The following solution solves the overflow problem:

2. print( (abs(Number)/2) + (Number/2) )

However, there may be a case in which Number is and must remain integer, and the division operator (/) is integer division, so that 7/2=3. In this case solution 2 won't work because if Number=7 it will print 6 (for this case solution 1 will work just fine).

So if we need to deal with both large numbers AND integer arithmetic, the following monstrosity comes to the rescue, adding compensation for the 1 that may be lost in the division by 2 in case of odd integer:

3. print( 
    ( (abs(Number)/2)+(Number/2) ) +
    ((
        (Number-(2*(Number/2))) + 
        (abs(Number)-(2*(abs(Number)/2)))
    ) / 2)
    )        
like image 112
Roee Adler Avatar answered Dec 09 '22 21:12

Roee Adler