Leetcode: Bitwise AND of Numbers Range
2015-12-15 02:14
417 查看
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4.
Analysis: O(N) solution will cause TLE, so this is a math problem and should generate O(1) solution
First trial: slow.
Check all 32 bits. see if both m(lower bound) and n(higher bound) are 1 on ith bit. Also need to check if diff=n-m+1 is greater than 2^i, which is the max range that 1 is fixed on this bit.
public class Solution { public int rangeBitwiseAnd(int m, int n) { int res = 0; int diff = n-m+1; int maxRange = 1; for (int i=0; i<=31; i++) { maxRange = (int)Math.pow(2, i); if (diff > maxRange) continue; int mi = (m>>i) & 1; int ni = (n>>i) & 1; if (mi == 1 && ni == 1) res |= 1<<i; } return res; } }
Better solution: this is actually finding the Shared Header(公共头部)
public class Solution { public int rangeBitwiseAnd(int m, int n) { if (m > n) return 0; int i = 0; while (m != n && m != 0) { m = m >> 1; n = n >> 1; i++; } return m<<i; } }
相关文章推荐
- background复合属性详解(上):background-image
- Maven编译32位Hadoop2.7.1
- awk 正则表达式、正则运算符详细介绍
- HDU 3016 线段树单点更新+DP
- 296. Best Meeting Point
- ORACLE LINUX 5.11 UDEV绑定asm磁盘问题
- UVALive 6905 Two Yachts(费用流)
- awk单行脚本快速参考
- UVALive 6904 Travel Card(dp)
- glsl计算sprite的亮度饱和度对比度
- mysql =》 mysql 命令恢复数据库
- 高精度数字
- UVALive 6902 Three Squares(二分 + 搜索)
- runtime——函数替换
- [蓝牙] 5、Battery Service module
- UVALive 6901 String Transformation(贪心)
- 例题5-1 UVA 10474 Where is the Marble?大理石在哪?
- mysql => mysql数据库备份 命令
- 【Beta阶段】第三次Scrum Meeting!
- 基本类型