How to check if a number is power of two using BIT Manipulation?

 How to check if a number is the power of two using BIT Manipulation?


We will see here how we can check whether a number is the power of two using BIT Manipulation.
So what we can do is we can convert the given number into Binary.

Any number which is the power of 2 in binary will look like  10000...000 with only one 1 at the beginning and then only zero.
Now we will convert the given number - 1 into binary and it will look like 01111...111 means it will become one's complement of the given number.

Now if we take and of both the number we will get 0 and hence we can know that the given number is a power of 2.
Here is the code in C++.

The code starts from Solve function.


#include <bits/stdc++.h>

using namespace std;

#define int            long long int
#define F              first
#define S              second
#define pb             push_back
#define si             set <int>
#define vi             vector <int>
#define pii            pair <int, int>
#define vpi            vector <pii>
#define vpp            vector <pair<int, pii>>
#define mii            map <int, int>
#define mpi            map <pii, int>
#define spi            set <pii>
#define endl           "\n"
#define sz(x)          ((int) x.size())
#define all(p)         p.begin(), p.end()
#define double         long double
#define que_max        priority_queue <int>
#define que_min        priority_queue <int, vi, greater<int>>
#define bug(...)       __f (#__VA_ARGS__, __VA_ARGS__)
#define print(a)       for(auto x : a) cout << x << " "; cout << endl
#define print1(a)      for(auto x : a) cout << x.F << " " << x.S << endl
#define print2(a,x,y)  for(int i = x; i < y; i++) cout<< a[i]<< " "; cout << endl


void solve() {

int n;
cin>>n;

if((& (n-1))==0){
    cout<<"The number is power of 2"<<endl;
}
else{
    cout<<"The number is Not power of 2"<<endl;
}




}

int32_t main()
{
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);


  clock_t z = clock();

  int t = 1;
//   cin >> t;
  while (t--) solve();



  return 0;
}


Thank you for reading this.

Post a Comment

0 Comments