Finding if a number is a power of 2

前端 未结 7 1180
孤城傲影
孤城傲影 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条回答
  • Subtract 1 from the number, then and it with the original number. If the result is zero, it was a power of two.

    if (((n-1) & n) == 0) {
        // power of two!
    }
    

    (sorry, my PHP is rusty...)

    0 讨论(0)
  • 2021-02-18 18:39

    If it's a power of 2? Well, one way is to convert it to binary, and verify the presence of only 1 1...:

    $bin = decbin($number);
    if (preg_match('/^0*10*$/', $bin)) {
        //Even Power Of 2
    }
    
    0 讨论(0)
  • 2021-02-18 18:39

    In a binary equivalent of any decimal number which is a power of two will have only one occurrence of 1 in its binary equivalent.

    <?php
        $number = 4096;
        $bin = decbin($number);
        if ($number != 1 && substr_count($bin,1) == 1) {
            echo "Yes";
        } else {
            echo "No";
        }
    ?>
    
    0 讨论(0)
  • 2021-02-18 18:40
    Math.log(x)/Math.log(2) == Math.floor(Math.log(x)/Math.log(2))
    
    0 讨论(0)
  • 2021-02-18 18:42

    One way is to use bitwise AND. If a number $x is a power of two (e.g., 8=1000), it will have no bits in common with its predecessor (7=0111). So you can write:

    ($x & ($x - 1)) == 0
    

    Note: This will give a false positive for $x == 0.

    0 讨论(0)
  • 2021-02-18 18:46

    The top answer:

    ($x & ($x - 1)) == 0
    

    seemed to have issues with larger numbers for me, this works well for larger numbers using the same logic but with GMP:

    gmp_strval(gmp_and($x, gmp_sub($x, 1))) == 0
    
    0 讨论(0)
提交回复
热议问题