LeetCode *342.Power of Four (Python Solution)

本文提供了一种高效的算法解决方案,用于判断一个32位带符号整数是否为4的幂。通过深入分析4的幂的特性,提出了三种不同的Python实现方法,包括位运算和二进制计数,以及一个巧妙的数学归纳法验证。

题目描述

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

给定一个整数(带符号的32位),写一个函数来检查它是否为4的幂。

Example 1:

Input: 16
Output: true

Example 2:

Input: 5
Output: false


Python Solution

**分析:**由题目易得知 4 的幂一定是 2 的幂,所以在上一篇LeetCod*231 Power of Two的基础上对代码进行改动。

solution 1

继续进行位运算,利用0x55555555来和自身做 & 运算并和自身作对比。

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and n & (n - 1) == 0 and (n & 0x55555555) == n
solution 2

在之前的基础上观察 4 的幂转化为二进制后, 0 的个数都为偶数个,所以加个判断条件就好。

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and  bin(n).count('1‘) == 1 and bin(n).count('0') % 2 == 1

还没完还没完,接下来:

炫技时刻

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

其实也还好,就是思维要绕个弯,数学归纳法即可证得。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值