342. Power of Four [easy] (Python)

该博客主要介绍了LeetCode上的342题——Power of Four。内容包括题目的链接、原题描述、中文翻译,以及五种不同的解题思路,包括使用循环和递归的方法,以及满足无循环、无递归要求的解决方案。解题思路涉及到将整数转换为二进制并分析其特性来判断是否为4的幂次。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

https://leetcode.com/problems/power-of-four/

题目原文

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

题目翻译

给定一个整数(有符号32位),写个函数判断它是否是4的倍数。比如:输入16,返回true;输入5,返回false。
进一步:你能不用循环或递归解决吗?

思路方法

思路一

先不考虑进一步的要求,用循环的方法求解。

代码

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 0:
            return False
        while num%4 == 0:
            num /= 4
        return num == 1

思路二

先不考虑进一步的要求,用递归的方法求解。

代码

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 0:
            return False
        if num == 1:
            return True
        if num%4 == 0:
            return self.isPowerOfFour(num/4)
        else:
            return False

思路三

题目说了不能循环或递归,上面的解法能AC但不太符合题意。考虑到输入是“Integer”,是有范围的(<2147483648),所以算出能输入的所有4的幂次,保存到list或dict中,对每次输入判断是否在这些数中即可。

代码

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        nums = [1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824]
        return num in nums

思路四

4的幂次表现在二进制上,为首位为1,后面有偶数个0。所以先将输入的数转换成2进制,再判断2进制中0和1的个数即可。
注意:Python里将数转成二进制后的表示为“0bxxxx”,最前面有个0,在计算0的个数时要考虑到。

代码

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        return num > 0 and bin(num).count('1') == 1 and bin(num).count('0') % 2 == 1

思路五

类似思路四,我们可以先判断输入数的二进制形式为1后面若干个0,再判断1是否在奇数位即可。

代码

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        return num > 0 and num&(num-1) == 0 and (num & 0x55555555) != 0

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51505994

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值