PROBLEM:
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?
SOLVE:
class Solution {
public:
bool isPowerOfThree(int n) {
return n>0&&1162261467%n==0;
}
};
class Solution {
public:
bool isPowerOfThree(int n) {
return fmod(log10(n)/log10(3), 1)==0;
}
};
解释一下:1162261467 是int中最大的3的幂,fmod(a,b)获得a-b的余数。
假如判断是否为4的幂呢?此时,方法1不可用,因为最大4的幂级数能被2的幂级数整除,但有方法如下:
class Solution {
public:
bool isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
}
};
稍微解释一下:第二个条件是因为最小的4的幂级数为1,接着为100,10000,所以其中只有一个1,所以减1后自然是将各位反了一下(这步将2的幂级数和4的幂级数选了出来);第三个可以将公式拆为
4^n - 1 = (2^n + 1) * (2^n - 1),因为每连续三个数中必有一个数是3的倍数(这部将2的幂级数排除)。