Do the below without any conditional or comparison operator.
if (Number <= 0)
{
Print '0';
}
else
{
print Number;
}
thanks..
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With