[LeetCode] 342. Power of Four 4的次方数
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?
Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.
给一个有符号的32位整数,写一个函数检查此数是否为4的次方数。
解法1:位操作
解法2:循环
解法3: 数学函数, 换底公式
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public boolean isPowerOfFour( int num) { int count0= 0 ; int count1= 0 ; while (num> 0 ){ if ((num& 1 )== 1 ){ count1++; } else { count0++; } num>>= 1 ; } return count1== 1 && (count0% 2 == 0 ); } |
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public boolean isPowerOfFour( int num) { while (num> 0 ){ if (num== 1 ){ return true ; } if (num% 4 != 0 ){ return false ; } else { num=num/ 4 ; } } return false ; } |
Java:
1 2 3 4 5 6 7 8 9 10 | public boolean isPowerOfFour( int num) { if (num== 0 ) return false ; int pow = ( int ) (Math.log(num) / Math.log( 4 )); if (num==Math.pow( 4 , pow)){ return true ; } else { return false ; } } |
Python:
1 2 3 4 5 6 7 8 | class Solution( object ): def isPowerOfFour( self , num): """ :type num: int :rtype: bool """ return num > 0 and (num & (num - 1 )) = = 0 and \ ((num & 0b01010101010101010101010101010101 ) = = num) |
Python:
1 2 3 4 5 6 7 8 9 10 11 | # Time: O(1) # Space: O(1) class Solution2( object ): def isPowerOfFour( self , num): """ :type num: int :rtype: bool """ while num and not (num & 0b11 ): num >> = 2 return (num = = 1 ) |
C++:
1 2 3 4 5 6 7 8 9 | class Solution { public : bool isPowerOfFour( int num) { while (num && (num % 4 == 0)) { num /= 4; } return num == 1; } }; |
C++:
1 2 3 4 5 6 | class Solution { public : bool isPowerOfFour( int num) { return num > 0 && int ( log10 (num) / log10 (4)) - log10 (num) / log10 (4) == 0; } }; |
C++:
1 2 3 4 5 6 | class Solution { public : bool isPowerOfFour( int num) { return num > 0 && !(num & (num - 1)) && (num & 0x55555555) == num; } }; |
C++:
1 2 3 4 5 6 | class Solution { public : bool isPowerOfFour( int num) { return num > 0 && !(num & (num - 1)) && (num - 1) % 3 == 0; } }; |
类似题目:
[LeetCode] 231. Power of Two 2的次方数
[LeetCode] 326. Power of Three 3的次方数
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步