leetcode刷题笔记326 3的幂

leetcode刷题笔记326 3的幂

题目描述:

给出一个整数,写一个函数来确定这个数是不是3的一个幂。

后续挑战:
你能不使用循环或者递归完成本题吗?

题目分析:

既然不使用循环或者递归,那我可要抖机灵了

如果某个数n为3的幂 ,则k=log3N

代码思路:

首先求出int范围最大的3的幂   Max3

如果n为3的幂,则Max3必定能整除n

so,直接上代码

解答代码:

C++版:

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0)return false;
        const int maxint=0x7fffffff;
        int k=log(maxint)/log(3);
        int b3=pow(3,k);
        return (b3%n==0);
    }
};
Code

Python版:

class Solution:
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        maxint = 0x7fffffff

        k=math.log(maxint)//math.log(3)
        b3=3**k
        return (b3%n)==0
Code