Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
vector<int> powTwo;
bool isPowerOfTwo(int n) {
vector<int> powTwo;
int i;
for(i=0; i<31; i++)
{
int a = (1 << i);
powTwo.push_back(a);
}
vector<int>::iterator l, r;
l = lower_bound(powTwo.begin(), powTwo.end(), n);
r = upper_bound(powTwo.begin(), powTwo.end(), n);
if(l == r-1)
return true;
else
return false;
}
};
class Solution {
public:
vector<int> powTwo;
bool isPowerOfTwo(int n) {
vector<int> powTwo;
int i;
for(i=0; i<31; i++)
{
int a = (1 << i);
powTwo.push_back(a);
}
int m = binary_search(powTwo.begin(), powTwo.end(), n);
if(m == 1)
return true;
else
return false;
}
};
#include "iostream"
#include "algorithm"
using namespace std;
int main()
{
int a[] = {2, 7, 7, 7, 11};
// 正常情况
int l = lower_bound(a, a+5, 7) - a;
int u = upper_bound(a, a+5, 7) - a;
int c = binary_search(a, a+5, 7);
cout << l << " " << u << " " << c << endl;
// 找比数组中最小数还小的数
int l1 = lower_bound(a, a+5, 1) - a;
int u1 = upper_bound(a, a+5, 1) - a;
int c1 = binary_search(a, a+5, 1);
cout << l1 << " " << u1 << " " << c1 << endl;
// 找比数组中最大数还大的数
int l2 = lower_bound(a, a+5, 16) - a;
int u2 = upper_bound(a, a+5, 16) - a;
int c2 = binary_search(a, a+5, 16);
cout << l2 << " " << u2 << " " << c2 << endl;
// 找不超出数组数值范围,但不位于数组中的数字
int l3 = lower_bound(a, a+5, 8) - a;
int u3 = upper_bound(a, a+5, 8) - a;
int c3 = binary_search(a, a+5, 8);
cout << l3 << " " << u3 << " " << c3 << endl;
return 0;
}