Program To Check Power Of 2

Prashant | Fri, 12 Jun, 2020 | 543

Program to check a number is power of 2 or not

We provide you the best optimal solutions of each and every question, so no need to worry just learn with fun with us smiley.

Question :- 

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). 

Best Optimal solution :-

We will solve this question using builtin function __builtin_popcount() which just counts the number of 1s in the binary representation of a number.

for example of we have number = 3 so its binary representation will be :- 011 so it contains two 1s in it, so popcount will count the number of 1s in it.

So if a number if power of two then it is only going to have only one 1, 

lets see :- 

2 -> 0010

4 -> 0100

8 -> 1000 

similarly all power of two contains only one 1 in its binary representation.

Best Optimal solution :- 

#include<bits>
using namespace std;
int main()
{
	int t;
	cin>>t;
	while(t--){
	    long long int n;
	    cin>>n;
	    int num=__builtin_popcountll(n);  // present in algorithm.h header file
    
        if(num==1)
        cout<<"YES";
        else cout<<"NO";
    
        cout<<endl;
	}
	
	return 0;
}

 

0 comments
Leave a comment