Problem:
Given an integer, write a function to determine if it is a power of three.
Could you do it without using any loop / recursion?
Summary:
用非循环/递归的方法判断数n是否为3的整数幂。
Analysis:
1. 循环:将n逐次除以3,判断是否为3的整数幂。
class Solution {
public:
bool isPowerOfThree(int n) {
if (n <= ) {
return false;
}
while (n > ) {
if (n % ) {
return false;
} n /= ;
} return true;
}
};
2. 递归:若n为3的整数幂,n/3必为3的整数幂,以这个思想构建递归。
class Solution {
public:
bool isPowerOfThree(int n) {
if (n <= ) {
return false;
} if (n == ) {
return true;
} return (n % == ) && isPowerOfThree(n / );
}
};
3. 非循环/递归:n若为3的整数幂,则 n = 3log3n = 3log2n / log 23
class Solution {
public:
bool isPowerOfThree(int n) {
return (n > ) && (n == pow(, round(log(n) / log())));
}
};