Skip to content

Latest commit

 

History

History
73 lines (51 loc) · 1.83 KB

File metadata and controls

73 lines (51 loc) · 1.83 KB

https://leetcode-cn.com/problems/power-of-four/solution/3424de-mi-kao-lu-na-yao-duo-gan-ma-while-5gi8/

难度:简单

题目:

给定一个整数,写一个函数来判断它是否是 4 的幂次方。如果是,返回 true ;否则,返回 false 。

整数 n 是 4 的幂次方需满足:存在整数 x 使得 n == 4 ** x

提示:

-2 ** 31 <= n <= 2 ** 31 - 1

示例:

示例 1:
输入:n = 16
输出:true

示例 2:
输入:n = 5
输出:false

示例 3:
输入:n = 1
输出:true

分析

这有啥分析的?不就是预防老年痴呆 + 强制达标每日一题拿勋章吗? 哈哈...

基础循环解题:

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        mi = 0
        while 4 ** mi <= n:
            if n == 4 ** mi:
                return True
            mi += 1
        return False

强上高地解题:

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        return n in [1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,
                     16777216, 67108864, 268435456, 1073741824, 4294967296]

判断幂与整除

class Solution:
    def isPowerOfFour(self, n):
        return n > 0 and (n & (n-1)) == 0 and n % 3 == 1

欢迎关注我的公众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。

有喜欢力扣刷题的小伙伴可以加我微信(King_Uranus)互相鼓励,共同进步,一起玩转超级码力!

我的个人博客:https://qingfengpython.cn

力扣解题合集:https://github.com/BreezePython/AlgorithmMarkdown