Power of Three

Given an integer, write a function to determine if it is a power of three.

Follow up:
Could you do it without using any loop / recursion?

Credits:

Special thanks to @dietpepsi for adding this problem and creating all test cases.


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

bool judge(int n);
int main()
{
	int a[] = { 3, 27, 30, 81, 88,243 };
	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 && (n % 3 == 0))
	{
		n = n / 3;
	}
	return n == 1;*/
	//判断一个数是不是整数(int)a-a==0  则是整数
	/*return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0);*/
	
	while (n % 3 == 0) n /= 3;
	return n == 1;
}


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