how to find the previous number which is a power of 2 program code example
Example 1: 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;
}
}
Example 2: powers of 2 in cpp
int main() {
int ans = 1 >> n;
}
void power(int x, int y) {
int ans = 1;
for (int i = 0; i < y; i++) {
ans *= x;
}
return ans;
}