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的冪級數排除)。