Check if the number is power of 2 i.e num == 2^x where x can be any number.

Solution

  • Total bits must be 1.
  • Count the bits / use & operator with the number previous to it.
  • If the output is 0 the number is power of 2.

Python

num = int(input("Enter a number: "))
 
if num > 0 and num & (num-1) == 0:
    print(f"num {num} is a power of 2")
else:
    print(f"num {num} is not a power of 2")

CPP

#include <iostream>
 
using namespace std;
 
int main() {
  int n;
  cout << "Enter a number";
  cin >> n;
 
  if (n > 0 && (n & (n - 1)) == 0) {
    cout << "Yes";
  } else {
    cout << "No";
  }
}