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 @yukuairoyfor 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;
}
};

   

类似题目:

[LeetCode] 231. Power of Two 2的次方数

[LeetCode] 326. Power of Three 3的次方数

All LeetCode Questions List 题目汇总

最新文章

  1. 使用hibernate可以优化的地方
  2. 高性能 Windows Socket 组件 HP-Socket v2.3.1-beta-1 发布
  3. 12个css高级技巧.html
  4. iframe 子页面获取父页面的元素并且控制样式
  5. POJ 2253 Frogger(floyd)
  6. Java编程陷阱-类成员初始化
  7. Ubuntu通过使用PyCharm 执行调试 Odoo 8.0 可能的问题
  8. JVM之垃圾回收
  9. js如何调用php文件内显示的数值到html?
  10. zimbra填坑记录
  11. Spark RDD Action 简单用例(一)
  12. day06作业---字典循环
  13. liferay中如何实现自己定义的方法
  14. 分散/聚集IO(scatter/gather)及iovec结构体
  15. c# 前后日期设置
  16. java并发之Lock以及和synchronized区别
  17. number 解题报告
  18. Using ASIHTTPRequest in an iOS project
  19. centos7设置ip
  20. GTY's gay friends 线段树判断区间是否有相同数字

热门文章

  1. Python 爬虫js加密破解(四) 360云盘登录password加密
  2. Java 出现cannot be resolved to a type
  3. HDU - 5513 Efficient Tree(轮廓线DP)
  4. Tomcat启动服务报错:Unknown version string [4.0]. Default version will be used.
  5. java web项目改装exe安装版
  6. “知乎杯”2018 CCF 大学生计算机系统与程序设计竞赛 贪心算法(greedy)
  7. (9)Go指针
  8. 新版本Mariadb安装后相关问题的解决
  9. Kubernetes kubectl 命令概述
  10. 20189220 余超《Linux内核原理与分析》第二周作业