#142 O(1) Check Power of 2

来源:互联网 发布:linux oracle多实例 编辑:程序博客网 时间:2024/05/14 08:59

题目描述:

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

题目思路:

每个int32都一共只有32位,而如果是2的power,那么这32位中必须只有一位是‘1’。

Mycode(AC = 39ms):

class Solution {public:    /*     * @param n: An integer     * @return: True or false     */    bool checkPowerOf2(int n) {        // write your code here        long long ln = (long long)n;        if (ln < 0) return false;                // traverse all the 32 bits, the result        // should only contain one '1'        int count = 0;        for (int i = 0; i < 32; i++) {            count += ln % 2;            ln >>= 1;        }                return count == 1;    }};


0 0
原创粉丝点击