Bitwise AND of Numbers Range -- LeetCode, leetcode
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 shoshould return 4.
Train of Thought: the first train of thought must start with bitwise AND from the first number, but the complexity is too high and new improvements are made. If there is a power of 2 in this range, from this point on, the power of the 2 is equal to n. If the power of the 2 is smaller than m, the installation or installation will start from this range.
int rangeBitwiseAnd(int m, int n) {int i;int result ;for(i=0;;i++)if(pow(2,i)>n)break;if(pow(2,i-1) < m){result = m;for(i=m+1;i<=n;i++) result &= i; } else{result = pow(2,i-1);i = pow(2,i-1)+1;for(;i<=n;i++) result &= i;} return result;}
Looking at other people's code, we can find that there is a faster speed. For a continuous digital sequence, the last two adjacent numbers must be different, so as long as m! = N, then the last digit must be 0, so we can see from which one starts m = n.
int rangeBitwiseAnd(int m, int n) { int offset = 0; while (m && n) { if (m == n) { return m << offset; } m >>= 1; n >>= 1; offset++; } return 0; }