Power of Two & Power of Three & Power of Four
2016-07-23 02:59
387 查看
Check Power of 2
Using O(1) time to check whether an integer n is a power of
Example
For
For
奇数总是有超过2个1.
Check Power of 3
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
Check Power of 4
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.
Explanation:
The magic numbers might seem very confusing. But they are not random (obviously!). Let us start with 0X55555555. Binary representation of 5 is 0101. So 0X55555555 has 16 ones, 16 zeros and the ones,zeros take alternate positions.
Using O(1) time to check whether an integer n is a power of
2.
Example
For
n=4, return
true;
For
n=5, return
false;
奇数总是有超过2个1.
class Solution { public boolean checkPowerOf2(int n) { if(n <= 0) return false; return (n & (n - 1)) == 0 ? true : false; } };
Check Power of 3
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
public class Solution { public boolean isPowerOfThree(int n) { if (n == 0) return false; if (n == 1) return true; if (n > 1) return n % 3 == 0 && isPowerOfThree(n / 3); else return false; } }
Check Power of 4
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.
private boolean smartBit(long num){ return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x5555555555555555l) == num); }
Explanation:
The magic numbers might seem very confusing. But they are not random (obviously!). Let us start with 0X55555555. Binary representation of 5 is 0101. So 0X55555555 has 16 ones, 16 zeros and the ones,zeros take alternate positions.
相关文章推荐
- 优雅的懒加载方法
- window消息处理模块
- Regular Expression Matching & Wildcard Matching
- 给自己技术发展之路上的意见
- mybatis_SQL映射(2)
- 守护进程详细解读
- 大数计算
- 安装vs2013的entityframework
- 2016 Multi-University Training Contest 1 -1006 PowMod
- 串口通信的基本概念
- SparseArray解析
- php基础和http知识介绍
- 插件框架篇之Activity中theme、launchMode等设置问题
- if else
- UITableView的性能优化? 滑动的时候有种卡的感觉是为什么?怎么解决?
- 富文本
- python变量
- Android群英传之Android绘图机制与处理技巧
- Basic_Android关于buildToolVersion与CompileSdkVersion
- python变量