题目来源【Leetcode】
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?
这道题要求不用循环来判断这个数是否为3的N次方
方法一: 用取对数的办法 n = 3^i;最后就是证明log10(n)/log10(3)是否为整数
class Solution {
public:
bool isPowerOfThree(int n) {
double i = log10(n)/log10(3);
return ((i-(int)i)== 0);
}
};
方法二:根据能够表示最大3的N次方的数来除n:
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467%n == 0 ;
}
};