比特位操作——O(1)时间检测2的幂次
2017-06-27 20:12
429 查看
转自:http://blog.csdn.net/shinanhualiu/article/details/49004139
用 O(1) 时间检测整数 n 是否是 2 的幂次。
您在真实的面试中是否遇到过这个题?
Yes
样例
solution: 在O(1)时间内判断一个整数是否为2的幂次,只能使用位操作。因为2的幂次数其二进制表示中1的个数只有一个而其他的数则没有这情况。而2的幂次减1除了那位为0其他位为1。
例如:
2 = (10)2 —->
1 = (01)2
4 = (100)2 —->
3 = (011)2
8 = (1000)2 —->
7 = (0111)2
用 O(1) 时间检测整数 n 是否是 2 的幂次。
您在真实的面试中是否遇到过这个题?
Yes
样例
n=4,返回
true;
n=5,返回
false.
solution: 在O(1)时间内判断一个整数是否为2的幂次,只能使用位操作。因为2的幂次数其二进制表示中1的个数只有一个而其他的数则没有这情况。而2的幂次减1除了那位为0其他位为1。
例如:
2 = (10)2 —->
1 = (01)2
4 = (100)2 —->
3 = (011)2
8 = (1000)2 —->
7 = (0111)2
public class CheckPowerOf2 { public boolean checkPowerOf2(int n){ if(n<=0) return false; return (n&(n-1))==0; } }
相关文章推荐
- 百度高度js 检测web页面是否正在操作,如超过规定时间内未操作将自动跳转至指定页面。
- LintCode 142. O(1)时间检测2的幂次
- js实现检测当前时间是否超过指定时间,而进行操作
- 【LintCode 简单】142. O(1)时间检测2的幂次
- Android通过ping操作进行网络检测,并返回花费的时间
- O(1)时间检测2的幂次
- Java实现-O(1)时间检测2的幂次
- 142-时间检测2的幂次
- O(1)时间检测2的幂次
- 2的次方(去哪儿2017校招真题) & O(1)时间检测2的幂次(LintCode)
- 用 O(1) 时间检测整数 n 是否是 2 的幂次。
- LintCode :O(1)时间检测2的幂次
- lintcode-142-O(1)时间检测2的幂次
- LintcodeO(1)时间检测2的幂次
- C#检测系统无操作时间与关闭计算机
- O(1)时间检测2的幂次-LintCode
- js 检测web页面是否正在操作,如超过规定时间内未操作将自动跳转至指定页面。
- LintCode:O(1)时间检测2的幂次
- python_lintcode_64合并排序数组 II_60搜索插入位置_142 O(1)时间检测2的幂次
- O(1)时间检测2的幂次