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,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步