【LeetCode】201. Bitwise AND of Numbers Range
Bitwise AND of Numbers Range
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.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
从m到n逐个做与操作肯定是不合理的,最多要进行INT_MAX*32次位与操作。
可以把复杂度降低到32次移位并处理。
对于每一位来说,只要中间存在一个0,该位就是0,只有全1的时候才是1.
因此问题变为:对于从右数第i位数字,从m到n之间是否全1?
满足全1要同时满足两个条件:
(1)m的相应位置是1 即起始位置必须是1
(2)m到n之间的间隔不大于m到最后一个连续1的间隔
class Solution { public: int rangeBitwiseAnd(int m, int n) { int ret = 0; int gap = n - m; if(gap == 0) return m; int bit = 1; //note that 0 <= m <= n <= 2147483647 //the highest bit must be 0, thus skip i == 31 for(int i = 0; i < 31; i ++) {//bit by bit check zero int ind = m % (int)pow(2.0, i+1); if((ind >= (int)pow(2.0, i)) && (ind+gap <= (int)pow(2.0, i+1)-1)) //all 1's ret |= bit; bit <<= 1; } return ret; } };