[LeetCode] Power of Two

Given an integer, write a function to determine if it is a power of two.

判断一个整数是否是2的幂。如果一个数是2的幂,则这个数的二进制表示中,最高位是1,其他位都是0。这个数-1的二进制位全是1。所以我们可以利用这个规律对两个数取与进行判断。

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n <= 0)
            return false;
        return !(n & (n - 1));
    }
};
// 3 ms

相关题目:Power of Three

相关题目:Power of Four

原文地址:https://www.cnblogs.com/immjc/p/7222956.html