leetcode之Power of Three

来源:互联网 发布:淘宝工艺品店铺介绍 编辑:程序博客网 时间:2024/05/22 13:56

道理同Power of Two.取对数是很巧妙的方法,来源于扎实的数学基础才能想出该巧妙的办法。

(1)C语言实现

bool isPowerOfThree(int n) {
    if(n<=0)
        return false;
    double n1 = log10(n)/log10(3);
    return n1-(int)n1==0;
}

(2)C++实现

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0)
            return false;
        while(n%3==0){
            n /= 3;
        }
        return n==1;
    }
};
/*解法二
class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0)
            return false;
        double n1 = log10(n)/log10(3);
        return n1-(int)n1==0;
    }
};
*/

(3)java实现

public class Solution {
    public boolean isPowerOfThree(int n) {
        if(n<=0)
            return false;
        while(n%3==0){
            n/=3;
        }
        return n==1;
    
    }
}

0 0
原创粉丝点击