how to check a number is power of 2 java code example
Example 1: java is power of 2
boolean result = number > 0 && ((number & (number - 1)) == 0);
Example 2: How to check whether the given number is a power of 2 in O(1)
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number :";
cin>>n;
if(n != 0 && (n & (n-1)) == 0)
{
cout<<"Number is power of 2"<<endl;
}
else
{
cout<<"Number is not power of 2"<<endl;
}
}