Write a C function that round up a number to next power of 2

后端 未结 7 1346
忘掉有多难
忘掉有多难 2021-01-04 12:53

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         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 13:09

    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 ORs).

提交回复
热议问题