Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.

 

#include<iostream>  
#include<algorithm>  
using namespace std;

bool judge(int n);
int main()
{
	int a[] = { 4, 16, 30, 64, 88, 24 };
	for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
	{
		cout << judge(a[i]) << endl;
	}


	system("pause");
	return 0;
}
bool judge(int n)
{
	/*while (n % 4 == 0)
		n = n / 4;
	return n == 1;*/
	return (n > 0 && int(log10(n) / log10(4)) - log10(n) / log10(4) == 0);
}


你可能感兴趣的:(Power of Four)