leetcode 342. 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?
解法1,经典的数学解法:
1 2 3 4 5 6 7 8 9 | class Solution( object ): def isPowerOfFour( self , num): """ :type num: int :rtype: bool """ if num < = 0 : return False n = int ( round (math.log(num, 4 ))) return 4 * * n = = num |
解法2,迭代:
1 2 3 4 5 6 7 8 9 10 11 12 | class Solution( object ): def isPowerOfFour( self , num): """ :type num: int :rtype: bool """ if num < = 0 : return False while num > = 4 : if num % 4 ! = 0 : return False num = num / 4 return num = = 1 |
解法3,最牛叉,
1 2 3 4 5 6 7 | class Solution( object ): def isPowerOfFour( self , num): """ :type num: int :rtype: bool """ return num > 0 and (num & (num - 1 )) = = 0 and (num - 1 ) % 3 = = 0 |
因为,4^n - 1 = C(n,1)*3 + C(n,2)*3^2 + C(n,3)*3^3 +.........+ C(n,n)*3^n
i.e (4^n - 1) = 3 * [ C(n,1) + C(n,2)*3 + C(n,3)*3^2 +.........+ C(n,n)*3^(n-1) ]
This implies that (4^n - 1) is multiple of 3.
类似解法:
1 | return n & (n - 1 ) = = 0 and n & 0xAAAAAAAA = = 0 |
或者是:
1 2 3 4 5 6 7 8 9 | class Solution( object ): def isPowerOfFour( self , n): """ :type num: int :rtype: bool """ #1, 100, 10000, 1000000, 100000000, .... #1, 100 | 10000 | 1000000 | 100000000, ... = 0101 0101 0101 0101 0101 0101 0101 0101 return n > 0 and n & (n - 1 ) = = 0 and (n & 0x55555555 ! = 0 ) |
因为n & n-1 == 0 就可以确定只有1个1, so 只要保证1的位置在1,3,5,7,。。。。这些位置上就行。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-06-20 EM算法——有隐含变量时,极大似然用梯度法搞不定只好来猜隐含变量期望值求max值了
2017-06-20 SVM最通俗的解读
2017-06-20 SVM中的线性分类器