Skip to content

Commit 2458138

Browse files
committed
Power of 2
1 parent 21a4884 commit 2458138

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Bit Manipulation/Power_of_2.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Given a non-negative integer N. The task is to check if N is a power of 2. More formally, check if N can be expressed as 2x for some x.
3+
4+
5+
Example 1:
6+
7+
Input: N = 1
8+
Output: true
9+
Explanation:
10+
1 is equal to 2 raised to 0 (20 = 1).*/
11+
//Initial Template for C++
12+
13+
#include<bits/stdc++.h>
14+
using namespace std;
15+
16+
// Function to check power of two
17+
bool isPowerofTwo(long long n){
18+
19+
// Your code here
20+
if(n==0)
21+
return 0;
22+
23+
else if(n>0)
24+
{
25+
if((n & n-1)==0)
26+
return 1;
27+
}
28+
return 0;
29+
}
30+
31+
// Driver code
32+
int main()
33+
{
34+
35+
int t;
36+
cin>>t;//testcases
37+
38+
for(int i=0;i<t;i++)
39+
{
40+
long long n; //input a number n
41+
cin>>n;
42+
43+
if(isPowerofTwo(n))//Now, if log2 produces an integer not decimal then we are sure raising 2 to this value
44+
cout<<"YES"<<endl;
45+
else
46+
cout<<"NO"<<endl;
47+
48+
}
49+
50+
return 0;
51+
}
52+
// } Driver Code Ends

0 commit comments

Comments
 (0)