previous | start | next

Solution

The trick involves using x >> 31 as a mask with the bitwise and: &.

(x >> 31) is 0 if x >= 0

(x >> 31) is 0xFFFFFFFF if x >= 0

We can use this to add 1 to x >> 1 only when x is odd and negative.

Here is the solution using only the allowed bit operators.

 /**
  * Computes x / 2 (integer division)
  * Examples: div2( 6,2) =  3
  *           div2( 5,2) =  2
  *           div2(-6,2) = -3
  *           div2(-5,2) = -2
  * Restrictions: Use only int constants that fit in 1 byte
  *               Use only << >> & +
  * Max operators: 12
  */
 int div2(int x)
 {
   int xs = x >> 31; /* 0 if x >= 0 and 0xFFFFFFFF if x < 0 */
   int y = x >> 1;   /* x / 2 if x is >= 0 or if x is even */
   int z = x & 1;    /* 1 if x is odd; otherwise 0 */

   return (xs & (y + z)) + (~xs & y);
   /* return 2; */
 }
   


previous | start | next