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?
題意:判斷一個數是否爲3的冪
思路:解決了2的冪以爲這個題也很簡單,一直取餘除三就行,但是看了看提議要求儘量不用遞歸和循環,所以就想用公式log3(n) = log(n)/log(3),看是否爲整數
坑:在c++中使用log函數是以e爲地的,提交了之後WA了,看了看disscuss說用log會有精度問題,然後又改,改成了log10,AC了。
收穫:
1、disscuss是一個好地方,很多坑別人都已經才過了,可以看看前人的經驗
2、modf的使用,把一個double分爲小數和整數部分。
cplusplus.com的例子
/* modf example */
#include <stdio.h> /* printf */
#include <math.h> /* modf */
int main ()
{
double param, fractpart, intpart;
param = 3.14159265;
fractpart = modf (param , &intpart);
printf ("%f = %f + %f \n", param, intpart, fractpart);
return 0;
}
Output:
3.141593 = 3.000000 + 0.141593
代碼:
class Solution {
public:
bool isPowerOfThree(int n) {
if(n == 0) return false;
double ans = (log10(n)/log10(3));
double x;
if(modf(ans,&x) == (double)0)
{
return true;
}
else
{
return false;
}
}
};