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 for adding this problem and creating all test cases.给一个有符号的32位整数,写一个函数检查此数是否为4的次方数。
解法1:位操作
解法2:循环
解法3: 数学函数, 换底公式
Java:
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:
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:
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:
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:
# 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++:
class Solution {public: bool isPowerOfFour(int num) { while (num && (num % 4 == 0)) { num /= 4; } return num == 1; }};
C++:
class Solution {public: bool isPowerOfFour(int num) { return num > 0 && int(log10(num) / log10(4)) - log10(num) / log10(4) == 0; }};
C++:
class Solution {public: bool isPowerOfFour(int num) { return num > 0 && !(num & (num - 1)) && (num & 0x55555555) == num; }};
C++:
class Solution {public: bool isPowerOfFour(int num) { return num > 0 && !(num & (num - 1)) && (num - 1) % 3 == 0; }};
类似题目: