p78 3的幂 (leetcode 326)

Posted repinkply

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了p78 3的幂 (leetcode 326)相关的知识,希望对你有一定的参考价值。

一:解题思路

方法一:可以采用前面讲解的类似的2的幂来做这道题,Time:O(log_3(n)),Space:O(1)

方法二:整数最大值,y=2^31-1。3^a<=y,那么a<=log_ay ==> a<=ln(y)/ln(3),计算出a为19.所以MAX_NUM=3^19。Time:O(1),Space:O(1)

二:完整代码示例 (C++版和Java版)

方法一C++:

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

方法一Java:

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

方法二C++:

class Solution {
public:
    int MAX_POWER = (int)(log(2147483647) / log(3));
    int MAX_NUM = (int)pow(3, MAX_POWER);

    bool isPowerOfThree(int n) 
    {
        return n > 0 && (MAX_NUM%n==0);
    }
};

方法二Java:

class Solution {
        private final int MAX_POWER=(int)(Math.log(Integer.MAX_VALUE)/Math.log(3));
        private final int MAX_NUM=(int)(Math.pow(3,MAX_POWER));
        public boolean isPowerOfThree(int n)
        {
               return n>0 && (MAX_NUM%n)==0;
        }
    }

 

以上是关于p78 3的幂 (leetcode 326)的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 326.3的幂 By Python

LeetCode 326 3的幂[数学 循环] HERODING的LeetCode之路

LeetCode刷题326-简单-3的幂

LeetCode刷题326-简单-3的幂

LeetCode326-3的幂(很奇妙的水题)

LeetCode 326. 3的幂 Power of Three