power of 2 Algorithm
In mathematics, a power of two is a number of the form 2n where N is an integer, that is, the consequence of exponentiation with number two as the base and integer N as the exponent. In a context where only integers are considered, N is restricted to non-negative values, so we have 1, 2, and 2 multiply by itself a certain number of times.
/*
* Given a number, determine if its power of 2 using bit manipulation in O(1)
*/
#include <iostream>
bool powerOfTwo( int n )
{
return (n > 0 && !( n & ( n - 1 ) ));
}
int main()
{
int n;
std::cout << "Enter a number :";
std::cin >> n;
if ( powerOfTwo(n) ) {
std::cout << n << " is power of 2\n";
} else {
std::cout << n << " is not power of 2\n";
}
return 0;
}