342. Power of Four
2016-07-14 22:23
337 查看
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.
如果一个数是2的幂次,它的二进制表示里面只有一位1.
如果一个数是4的幂次,同样它的二进制表示里面只有1位1,但是这个1位不能随意出现,4是100,16是10000,也就是隔位出现,把可能出现的位表示成一个数,用这个数去检查是不是4的幂次而排除例如8这样只是2的幂次的数。
public boolean isPowerOfFour(int num) {
return Integer.bitCount(num)==1&&((num&0x55555555)!=0);
}
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.
如果一个数是2的幂次,它的二进制表示里面只有一位1.
如果一个数是4的幂次,同样它的二进制表示里面只有1位1,但是这个1位不能随意出现,4是100,16是10000,也就是隔位出现,把可能出现的位表示成一个数,用这个数去检查是不是4的幂次而排除例如8这样只是2的幂次的数。
public boolean isPowerOfFour(int num) {
return Integer.bitCount(num)==1&&((num&0x55555555)!=0);
}
相关文章推荐
- 第二十天:规划风险应对
- Leetcode解题笔记(string)
- ros使用ssh配置远程
- 第二十天:规划风险应对
- 最小生成树
- 《javascript权威指南》读书笔记——第一篇
- RayeWang/MyView全文 收起
- html字符串转pdf源码
- POJ 1611 求节点0的强连通的节点个数
- SystemVerilog中结合interface实现输出数据总线的功能(1)
- Swift基本语法(4)-字符串
- 探讨Scala中的this.type
- 小项目组迭代开发流程
- 【题】【树状数组】NKOJ 3702 打鼹鼠
- 程序员调试能力提升
- 计算广告学学习1 - 广告的目的与效果
- Java垃圾回收机制
- 在WPF中使用配置文件(ConfigurationManager)
- PickerView居中,循环显示一系列
- Android中单例模式应用实战详解