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

后端 未结 7 1342
忘掉有多难
忘掉有多难 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

    Such questions always deserve counter questions to clarify requirements, if only to demonstrate your thinking and analytical skills and even creativity - that is what the interview should be about.

    For example in the absence of any specification that the "number" in question is necessarily an integer, you might propose the following:

    int nextPow2( double x )
    {
        return (int)pow( 2, ceil(log10(x) / log10(2))) ;
    }
    

    But if you did you might also express concern about the applicability of such a solution to an embedded system with possibly no floating-point unit.

提交回复
热议问题