I got the following question in an interview: \"Write a C function that round up a number to next power of 2.\"
I wrote the following answer:
#includ
The loop exits because you did not put parentheses around your condition. This should teach you not to put the unnecessary != 0
in your C/C++ conditions.
You can simplify your code quite a bit, though.
First, observe that temp
equals the prior value of num
, so you can change your loop to
int tmp;
do {
tmp = mum++;
} while (tmp & num); // Don't put unnecessary "!= 0"
Second, the interviewer was probably looking to see if you are familiar with this little trick:
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
Unlike your code that may take up to 1,000,000,000 operations to complete, the above always completes after twelve operations (a decrement, an increment, five shifts, and five OR
s).