Finding if a number is a power of 2

前端 未结 7 1347
孤城傲影
孤城傲影 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:32

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

提交回复
热议问题