leetcode 326. Power of Three 详解 python3

一.问题描述

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?

二.解题思路

这道题就是给一个数,看这个数是不是满足3^x=n, x是整数。

迭代来说,这道题有两种方法,一个是从n每次除3算到1,然后看看n还能不能整除3,最后当n=1的时候说明True.

另外一种是从1开始,每次乘3看看和n相等不,相等就True。

这道题主要的难点就是那个follow-up,不用循环做。

两种法子:

1.直接看log3(n)是不是一个整数,但是用python来求这个有精度误差,比如log3(243),正常来说结果应该是5,但是最后算出来的结果会是4.999999。我不知道其他语言是啥样,或者有啥其他的解决房子。(有的话麻烦评论告诉我)

2.用超过测试集中最大num的数3^t,即:3^(t-1)< max测试集<=3^t (在这个题中t是19)。

用3^t这个数去模n,能整除就说明是n是3的幂次方(注意剔除负数,因为比如说-3也是能被整除的,但是负数显然不是3的整数幂)。

原理: 素数幂只有一个质因子,这意味这素数幂这个数只能被这个素数的某个幂整除,不可能被其他数整除。

反过来将就是如果一个数能被素数幂整除,那么这个数肯定也是素数幂。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

1.迭代

# version 1
class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        i,res=1,False
        while i<=n:
            if i==n:
                res=True
                break
            else:i=(i<<1)+i
        return res

# version 2
class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n==0:return False
        while n!=1 and n==int(n):
            n=n/3
        return n==1

2.不用迭代

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n<=0:return False
        return 3**19%n==0
发布了218 篇原创文章 · 获赞 191 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/CSerwangjun/article/details/103315157