题目:
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?
思路:
1、带循环的:朴素解法,没什么特别的。时间复杂度是O(logn)。
2、不带循环的:我们首先定义一个在int范围内3的最大幂,然后判断n是否能够整除该最大幂即可,时间复杂度是O(1)。感觉这道题目有点流氓,因为我们也没法一下子写出来整数范围内3的最大幂是多少,还是需要通过循环来计算的。
代码:
1、带循环的:
class Solution {
public:
bool isPowerOfThree(int n) {
if(n <= 0) {
return false;
}
while(n > 1) {
if(n % 3 != 0) {
return false;
}
n /= 3;
}
return true;
}
};
2、不带循环的:
class Solution {
public:
bool isPowerOfThree(int n) {
int largest_power = 1162261467;
if(n <= 0 || n > largest_power) {
return false;
}
return largest_power % n == 0;
}
};