Interview Questions

given a 32-bit integer x.....

Microsoft Interview Questions and Answers


(Continued from previous question...)

26. given a 32-bit integer x.....

Question:
given a 32-bit integer x
find the smallest integer x0 > x
with the same number of ones in binary representation

Example:
x = 76
x0 = 81b

solution without loops and additional storage ?


maybe an answer:

given a number x = 1000111100
lo = x & -x; // locate the lowest set bit: lo = 100
lz = (x + lo) & ~x; // locate the lowest zero above lo: lz = 1000000
x += lo; // flip the 'lz' bit: x = 1001000000
x |= (lz / lo / 2); // add the rest number of ones: x = 1001000111

(Continued on next question...)

Other Interview Questions