check whether a given large number is an exponential of 2 or not code example

Example 1: How to check whether the given number is a power of 2 in O(1)

#include 
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"<

Example 2: powers of 2 in cpp

// If not using any extra libraries
// Powers of 2. If finding 2^n
int main() {
  int ans = 1 >> n;
}
// Suppose we want to find x ^ y
void power(int x, int y) {
  int ans = 1;
  for (int i = 0; i < y; i++) {
    ans *= x;
  }
  return ans;
}

Tags:

Misc Example