LintCode 题目:O(1)时间检测2的幂次

URL:https://www.lintcode.com/problem/o1-check-power-of-2/description

描述

用 O(1) 时间检测整数 n 是否是 2 的幂次。

O(1) 时间复杂度

您在真实的面试中是否遇到过这个题?  

样例

Example 1:
	Input: 4
	Output: true


Example 2:
	Input:  5
	Output: false

1.通过率:92%

在代码段中添加:

for (int i = 0; i < n; i++) {
            /* code */
            if(n==pow(2,i))
                return true;
        }
        return false;
    }

 即可:

原因:循环过多导致运行超时。

1.通过率:100%

思路:

2的次幂转换成二进制后,二进制序列中只有一个1。

在代码段中添加:

vector<int> arr;
        int tmp;
        if(n==0)
            arr.push_back('0');
        else{
            while(n!=0){
                tmp = n%2;
                arr.push_back(tmp);
                n /= 2;
            }
        }
        if(count(arr.begin(),arr.end(),1)==1)
            return true;
        else
            return false;

 即可:

发布了303 篇原创文章 · 获赞 550 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_42410605/article/details/103139738