Skip to content

Commit 6f1da55

Browse files
committed
isPowerOf2.cpp
This function will check whether a number is Power of 2 in O(1) time
1 parent 641c24b commit 6f1da55

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

BitManipulation/isPowerOf2.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include<iostream>
2+
3+
using namespace std;
4+
5+
bool isPowerOf2(int no)
6+
{
7+
if(no && (no & (no-1))==0) // lets the no is x.If x is power of 2,then x & (x-1) must be equal to zero
8+
return true;
9+
else // If x isn't power of 2,then x & (x-1) will be greater than or equal to x
10+
return false;
11+
}
12+
13+
int main()
14+
{
15+
int no; cin>>no;
16+
17+
if(isPowerOf2(no))
18+
cout<<"Yes\n";
19+
else
20+
cout<<"No\n";
21+
22+
return 0;
23+
}

0 commit comments

Comments
 (0)