Given a positive integer N. The task is to check if N is a power of 2. That is N is 2x for some x.
Input:
The first line contains T denoting the number of test cases. Each test case contains a single positive integer N.
Output:
Print "YES" if it is a power of 2 else "NO" (Without the double quotes).
Constraints:
1 <= T <= 100
0 <= N <= 1018
Example:
Input :
2
1
98
Output :
YES
NO
Explanation:
Testcase 1: 1 is equal to 2 raised to 0 (20 == 1).
Solution : The best solution is a little bit tricky. But it is O(1) solution which is the best. if N is the number then if the & operation of N & N-1 is 0 then it will be power of 2 else it will not. Example: 8. Binary is 1000 and binary of 7 is 0111. 1000 & 0111 is 0000. So 8 (2^3) is power of 2.
Code
#include<iostream>
using namespace std;
int main()
{
//code
long long int i,j,k,l,m,n,t;
cin>>t;
for(i=1;i<=t;i++)
{
cin>>n;
if(n>0)
{
k=n & n-1;
if(k==0)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
else
{
cout<<"NO"<<endl;
}
}
return 0;
}
Input:
The first line contains T denoting the number of test cases. Each test case contains a single positive integer N.
Output:
Print "YES" if it is a power of 2 else "NO" (Without the double quotes).
Constraints:
1 <= T <= 100
0 <= N <= 1018
Example:
Input :
2
1
98
Output :
YES
NO
Explanation:
Testcase 1: 1 is equal to 2 raised to 0 (20 == 1).
Solution : The best solution is a little bit tricky. But it is O(1) solution which is the best. if N is the number then if the & operation of N & N-1 is 0 then it will be power of 2 else it will not. Example: 8. Binary is 1000 and binary of 7 is 0111. 1000 & 0111 is 0000. So 8 (2^3) is power of 2.
Code
#include<iostream>
using namespace std;
int main()
{
//code
long long int i,j,k,l,m,n,t;
cin>>t;
for(i=1;i<=t;i++)
{
cin>>n;
if(n>0)
{
k=n & n-1;
if(k==0)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
else
{
cout<<"NO"<<endl;
}
}
return 0;
}
0 comments:
Post a Comment