326. Power of Three

    xiaoxiao2022-07-02  97

    Given an integer, write a function to determine if it is a power of three.

    Example 1:

    Input: 27

    Output: true

    Example 2:

    Input: 0

    Output: false

    Example 3:

    Input: 9

    Output: true

    Example 4:

    Input: 45

    Output: false

    Follow up:

    Could you do it without using any loop / recursion?

     

    思路参考这里

    最后还有一种巧妙的方法,利用对数的换底公式来做,高中学过的换底公式为logab = logcb / logca,那么如果n是3的倍数,则log3n一定是整数,我们利用换底公式可以写为log3n = log10n / log103,注意这里一定要用10为底数,不能用自然数或者2为底数,否则当n=243时会出错,原因请看这个帖子。现在问题就变成了判断log10n / log103是否为整数,在c++中判断数字a是否为整数,我们可以用 a - int(a) == 0 来判断,参见代码如下:

    class Solution { public: bool isPowerOfThree(int n) { return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0); } };

     

    最新回复(0)