Finding if a number is a power of 2

前端 未结 7 1182
孤城傲影
孤城傲影 2021-02-18 18:15

Just out of curiosity, how can you tell if a number x is a power of two (x = 2^n) without using recursion.

Thanks

相关标签:
7条回答
  • 2021-02-18 18:50

    For completeness, if the number is a float, you can test if it's a power of two by chacking if the mantissa is all zeros:

    <?php
    $number = 1.2379400392853803e27;
    $d = unpack("h*", pack("d", $number)); $d = reset($d);
    $isPowerOfTwo = substr($d, 0, 13) == "0000000000000";
    var_dump($isPowerOfTwo); // bool(true)
    

    Exercise for the reader: corner cases and big-endian machines.

    0 讨论(0)
提交回复
热议问题