Answer to Question #166077 in C++ for Sumeet

Question #166077

The "signature" of a function is the first line which gives the return type, the name of the function and the parameters with their types. As an example the signature of the gcd function is


int gcd(int m, int n)


Write a function with the following signature


bool is_power_of_two(int n)


It should return true if the n is a power of 2. Otherwise, it should return false. As an example, for n = 28, the function should return false while for n = 32, it should return true.



1
Expert's answer
2021-02-23T17:27:54-0500
#include <iostream>
 
using namespace std;
 
bool is_power_of_two(int n)
{
	for (int i = 2; i <= n;)
	{
		if (i == n) return true;
		i *= 2;
	}
	return false;
}
 
int main()
{
	cout << "Enter a number: ";
	int n = 0;
	cin >> n;
	cout << n << " is power of two: " << (is_power_of_two(n) ? "true" : "false") << endl;
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment