O(1) Check Power of 2

题目:

Using O(1) time to check whether an integer n is a power of 2.

分析:

这是一道背诵题。。但是在return那个语句中,不写好括号会出bug!!!

解法:

class Solution {
public:
    /*
     * @param n: An integer
     * @return: True or false
     */
    bool checkPowerOf2(int n) {
        // write your code here
        if (n <= 0) {
            return false;
        }
        if (n == 1) {
            return true;
        }
        return (n & (n - 1) ) == 0;
    }
};

results matching ""

    No results matching ""