码迷,mamicode.com
首页 > 其他好文 > 详细

O(1) Check Power of 2 - LintCode

时间:2015-05-27 12:04:04      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

examination questions

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

Example

For n=4, return true;

For n=5, return false;

Challenge

O(1) time


解题代码

class Solution {
public:
    /*
    * @param n: An integer
    * @return: True or false
    */
    bool checkPowerOf2(int n) {
    
        int t;
        int b;

        if (n == 1 || n == 2){
            return true;
        }
        if (n <= 0){
            return false;
        }

        while (true){
            t = n / 2;
            b = n % 2;
            if (b == 0){
                if (t == 2){
                    return true;
                }
                else{
                    n = t;
                }
            }
            else{
                return false;
            }
        }
    }
};

 

O(1) Check Power of 2 - LintCode

标签:

原文地址:http://www.cnblogs.com/hlwyfeng/p/4532828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!