Q:

C++ program to check if number is power of 2 using Bitwise operator

belongs to collection: C++ programs on various topics

0

C++ program to check if number is power of 2 using Bitwise operator

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C++ implementation

// program to find that the number is power of 2
#include<iostream>
using namespace std;

int main()
{
	// declaring the array n
	int n[]={4,9,15,16,20,22,25,32,45,64,72,80,100,128,256};
	int i;
	
	for(i=0;i<15;i++)
	{
		cout<< n[i] << " is power of 2 : ";
		// use of bitwise AND (&) operator
		if((n[i]& (n[i]-1))==0) 
			cout<<"True"<<endl;
		else
			cout<<"False"<<endl;
	}
	
	return 0;	
}

Output

 
4 is power of 2 : True 
9 is power of 2 : False
15 is power of 2 : False 
16 is power of 2 : True
20 is power of 2 : False 
22 is power of 2 : False 
25 is power of 2 : False 
32 is power of 2 : True
45 is power of 2 : False 
64 is power of 2 : True
72 is power of 2 : False 
80 is power of 2 : False 
100 is power of 2 : False
128 is power of 2 : True 
256 is power of 2 : True 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Implement Stack using Linked List in C++... >>
<< C++ program to print the left Rotation of the arra...