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;
即可: