[leetcode]326. Power of Three

[leetcode]326. Power of Three


Analysis

周五啦,端午小长假要开始啦~—— [嘻嘻~]

Given an integer, write a function to determine if it is a power of three.
判断一个数是不是3的指数幂。

Implement

方法一:(循环)

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

方法二:(在discussion里看到的一个大兄弟的解法,可以说是很6了,下面有提问问他在面试的时候怎么知道3的19的次方是1162261467,哈哈哈哈 笑死)

class Solution {
public:
    bool isPowerOfThree(int n) {
        return (n>0 && 1162261467%n==0);
    }
};

方法三:(用到了换底公式,logab = logcb/logca,所以只要判断log3n是不是整数就行了,不会插入公式,意会一下0。0)

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/80706395