leetcode326Power of Three
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?
使用遞歸或者循環是很簡單的。
class Solution {
public:
bool isPowerOfThree(int n) {
if (n <= 0)
{
return false;
}
if (n == 1)
{
return true;
}
return n % 3 == 0 && isPowerOfThree(n / 3);
}
};
題目中有比較高的要求不使用遞歸或者循環,那該怎麼辦呢,看了leetcode的幾個高投票的答案。
class Solution {
public:
bool isPowerOfThree(int n) {
double t = log10(n) / log10(3);
if (t == (int)t)
{
return true;
}
else
{
return false;
}
}
};
使用對數計算的方式,我特地去會議了下中學時學習的對數計算公式,在此做個例子就很好了解了。比如log10(3)和log10(9),log10(9) = log10(3x3) = log10(3) + log10(3);是以如果n是3的指數次幂的話,log10(n)的值一定是log10(3)的整數倍,很好了解了吧,科科。