O(1)时间检测2的幂次-LintCode

来源:互联网 发布:python 写shell脚本 编辑:程序博客网 时间:2024/05/27 00:32

用 O(1) 时间检测整数 n 是否是 2 的幂次。
样例
n=4,返回 true;
n=5,返回 false.
挑战
O(1) time

#ifndef C142_H#define C142_H#include<iostream>using namespace std;class Solution {public:    /*    * @param n: An integer    * @return: True or false    */    bool checkPowerOf2(int n) {        // write your code here        if (n == 1)            return true;        if (n <= 0)            return false;        if (n % 2 != 0)            return false;        else        {            if (checkPowerOf2(n >> 1))                return true;        }    }};#endif
原创粉丝点击