326. Power of Three
Given an integer, write a function to determine if it is a power ofthree.
Follow up:
Could you do it without using any loop / recursion?
判断一个数是否是3的幂,不适用循环和递归
利用对数换底公式,logab= logcb / logca。
log3n = log10n / log103,那么他们的商log3n一定是整数。
C++中判断一个数是否为整数 a - int(a) =0 则为整数。
class Solution {
public:
bool isPowerOfThree(int n){
returnint(log10(n)/log10(3))-(log10(n)/log10(3))==0;
}
};
而由于是INT型的,整数范围是0-231 ,所以,先求得在此范围内的最大的3的幂,是1162261467 (拓展,在Java中可以 Integer.MAX_VALUE=2147483647)
class Solution {
public:
bool isPowerOfThree(int n){
return (n>0 && 1162261467%n==0);
}
};