LeetCode 342. Power of Four(4的n次幂)
2016-04-30 11:08
274 查看
原题网址:342. Power of Four 342. Power of Four 342. Power of Four 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,并且1后面有偶数个0。
另一种实现:
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,并且1后面有偶数个0。
public class Solution { public boolean isPowerOfFour(int num) { return num > 0 && (num & -num) == num && (num & 0x55555555) != 0; } }
另一种实现:
public class Solution { public boolean isPowerOfFour(int num) { return num > 0 && (num & -num) == num && (num & 0x2AAAAAAA) == 0; } }
相关文章推荐
- 内存泄露
- POJ 3461 Oulipo
- B树和B+树
- 线性表的顺序存储结构(一)
- 设计模式 ( 二十 ) 访问者模式Visitor(对象行为型)
- 龙卷风
- nodejs概论(实操篇)
- 设计模式 ( 二十 ) 访问者模式Visitor(对象行为型)
- Java设计模式之观察者模式
- 设计模式 ( 十九 ) 模板方法模式Template method(类行为型)
- vector不是模板 || list不是模板解决办法
- mac下Tomcat安装及启动,浏览器却打不开解决方案
- 深入浅出ES6(十二):代理 Proxies
- 设计模式 ( 十九 ) 模板方法模式Template method(类行为型)
- Java多线程卖票例子
- Intellij Idea-最智能的java IDE
- 英语总结系列(十六):这个四月真不错
- 代码训练营——String
- 设计模式 ( 十八 ) 策略模式Strategy(对象行为型)
- 设计模式 ( 十七) 状态模式State(对象行为型)