類似的題解詳見:
leetcode_232. Power of Two分析
leetcode_342. Power of Four分析
題目鏈接
【題目】
Given an integer, write a function to determine if it is a power of three.
【分析】
解法1:
一般做法
class Solution {
public:
bool isPowerOfThree(int n) {
while (n && n % 3 == 0) {
n /= 3;
}
return n == 1;
}
};
解法2:
由於輸入是int,正數範圍是0-2**31,在此範圍中允許的最大的3的次方數爲319=1162261467,那麼我們只要看這個數能否被n整除即可
class Solution {
public:
bool isPowerOfThree(int n) {
return (n > 0 && 1162261467 % n == 0);
}
};
解法3:
根據解法2我們很容易想到的解法,就是將3**0 到3**19打表出來
class Solution {
public:
bool isPowerOfThree(int n) {
int power_list[20] = {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467};
for( int num:power_list )
if( num == n ) return true;
return false;
}
};
解法4:
這是discuss中一種比較巧妙地方法,利用我們數學中的換底公式
log a (b) = log c (b) / log c (a)
如果n是3的倍數,則log 3 (n)一定是整數,我們利用換底公式可以寫爲log 3 (n) = log 10 (n) / log 10 (3)
在c++中判斷數字a是否爲整數,我們可以用 a - int(a) == 0 來判斷
class Solution {
public:
bool isPowerOfThree(int n) {
return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0);
}
};