[leetcode] 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?

check n =? 3^x

Solution 1

Idea: divide 3 to see whether get 0 residue

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

Solution 2

Idea: if n=3^x, then log10(n) = xlog10(3), log10(n)/log10(3) is integer

class Solution {
public:
    bool isPowerOfThree(int n) {
        if (n < 0)
            return false;
        else{
            return (int(log10(n)/log10(3))-(log10(n)/log10(3)) ==0);
        }
        
    }
};



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/denny851108/article/details/51564572
文章标签: leetcode easy
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

[leetcode] 326. Power of Three

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭