previous | start | next

Finding the Answer

The answer is almost x >> 1.

If x is odd, then x / 2 mathematicall falls between two integers (7 / 2 is 3.5 which is between 3 and 4). Shifting to the right 1 bit will result in the smaller value 3. This is exactly what we want for positive integers.

But for x = -7, the value lies betwee -4 and -3. Shifting to the right 1 bit again gives the smaller value -4. But this is not what we want.

So the correct value for x / 2 could be computed by x >> 1 provided we add 1 when x is odd and negative.

If we could use 'if', and &&

Note x is odd if (x & 1) == 1

int div2(int x)
{    
 int y = x >> 1;
 if (x < 0 && ((x & 1) == 1) ) {
    y++;
 }
 return y;
}
     


previous | start | next