leetcode 342. Power of Four 判断一个数是否为4的幂
2016-04-23 17:22
381 查看
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?
这到题和Power of two类似,如果不能用递归循环做,就使用位操作。1个数是2的幂肯定是4的幂,但反过来不成立,4的幂只能是奇数位为1,而2的幂只有有一个位置为1就行。
所以先判断是否为2的幂,然后通过与.0X55555555(....1010101)进行&操作,保留奇数位,判断是否改变。
public boolean isPowerOfFour(int num) {
if(num<=0)
return false;
return (num & num-1)==0 && (num&0x55555555)==num;
}
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
这到题和Power of two类似,如果不能用递归循环做,就使用位操作。1个数是2的幂肯定是4的幂,但反过来不成立,4的幂只能是奇数位为1,而2的幂只有有一个位置为1就行。
所以先判断是否为2的幂,然后通过与.0X55555555(....1010101)进行&操作,保留奇数位,判断是否改变。
public boolean isPowerOfFour(int num) {
if(num<=0)
return false;
return (num & num-1)==0 && (num&0x55555555)==num;
}
相关文章推荐
- 【DS】数据结构--二叉树实现
- 利用Python与HFSS联合仿真设计一个微带天线
- 堆排序
- 创建maven父子工程
- 80秒验证13亿个身份证号码,包含省市县验证
- 【转】Struts1和Struts2的区别比较
- motto10
- 最长公共子序列问题
- MySQL 数据库 练习题
- 编程之美精确表达浮点数
- 工厂模式
- MySQL 数据库 常用函数
- 使用TexturePackerGUI配合NGUI打包图集
- 中外饮食类英语单词大全
- 背包问题-堆栈-找出其中一组解(总体积为T,n件物品体积分别是w1,w2,...,w2n,找出若干件恰好装满背包)
- Android Services 创建一个Bound服务
- 团队开发——个人工作总结05
- 全局侧滑
- 欢迎使用CSDN-markdown编辑器
- Eclipse下Genymotion模拟器的安装