326. Power 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?

判断给定整数是否是3的某次方。

分析:DONE

最简单的方法,反复迭代(即循环,但是题目不建议)

简单分析:

a)3^x,不管x正或者负,这个值一定大于0

b)如果一个数是3的x次方那么,反复除以3,最终一定等于1,return true

c)否则不是满足要求的数,return false

时间复杂度:O(lg(n)),空间复杂度:O(1)

class Solution {  
public:  
    bool isPowerOfThree(int n) {  
        int num=n;     
        while(num>0 && num%3==0)  
            num/=3;  
        return num==1;      
    }  
};  

2,和上面的思想一样:递归形式的解法(题目不建议)

时间复杂度:O(lg(n)),空间复杂度:O(lg(n))

class Solution {  
public:  
     
    bool isPow3(int n,int step) {  
        if(pow(3,step)==n)    
                return true;    
        if(pow(3,step)>n)    
                return false;    
        if(pow(3,step)<n)    
                return isPow3(n,++step);   
    }  
    bool isPowerOfThree(int n) {  
        int step=0;  
        return isPow3(n,step);  
    }  
};  

不用任何循环:(参考讨论区)

3,任何一个3的x次方一定能被int型里最大的3的x次方整除,如下所示

return n>0?!(1162261467 % n):0;

4,或者直接列举:

因为n是int型整数,所以其内满足要求的数还不到32个(2的x次方才32个),所以可以直接列举

class Solution {  
public:  
    bool isPowerOfThree(int n) {  
        return (n == 1 || n == 3 || n == 9 || n == 27 || n == 81 || n == 243 || n == 729 || n == 2187 || n == 6561 || n == 19683 || n == 59049 || n == 177147 || n == 531441 || n == 1594323 || n == 4782969 || n == 14348907 || n == 43046721 || n == 129140163 || n == 387420489 || n == 1162261467);  
    }  
};  

5,log函数

一个基本的事实就是如果n是3的x次方,那么以3为低对数后一定是一个整数,否则不是

class Solution {  
public:  
    bool isPowerOfThree(int n) {  
        double res = log10(n) / log10(3);  //有精度问题,不要用以指数2.718为低的log函数  
        return (res - int(res) == 0) ? true : false;  
    }  
};  
原文地址:https://www.cnblogs.com/blackiesong/p/6406606.html