Q:

Write a C++ program to check whether a given number is a power of two or not

0

Write a C++ program to check whether a given number is a power of two or not

Sample Output:

Is 8 is power of 2: True
Is 256 is power of 2: True
Is 124 is power of 2: False

All Answers

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

#include <iostream>
#include <cmath>
using namespace std;
string Powers_of_Two(int n) {

	for (int x = 0; x < INT_MAX; x++)
	{
		if (pow(2, x) == n)
		{
			return "True";
		}
		else if (pow(2, x) > n)
		{
			break;
		}
	}

	return "False";
}
int main() {
	cout << "Is 8 is power of 2: " << Powers_of_Two(8) << endl;
	cout << "Is 256 is power of 2: " << Powers_of_Two(256) << endl;
	cout << "Is 124 is power of 2: " << Powers_of_Two(124) << endl;
	return 0;
}

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

total answers (1)

Similar questions


need a help?


find thousands of online teachers now