That's simple:
inline bool isPowerOf2(int i)
{
return i > 0 && (i & (i - 1)) == 0;
}
Source:
http://www.parashift.com/c++-faq-lite/intrinsic-types.html#faq-26.12#include <iostream>
using namespace std;
inline bool isPowerOf2(int i)
{
return i > 0 && (i & (i - 1)) == 0;
}
int main()
{
cout << "64 is " << (isPowerOf2(64) ? "" : " not ") << "power of 2" << endl;
cout << "100 is " << (isPowerOf2(100) ? "" : " not ") << "power of 2" << endl;
cout << "128 is " << (isPowerOf2(128) ? "" : " not ") << "power of 2" << endl;
cout << "1024 is " << (isPowerOf2(1024) ? "" : " not ") << "power of 2" << endl;
return 0;
}
No comments:
Post a Comment