Topic:
Given a range [M, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, Inclus Ive.
For example, given the range [5, 7], and you should return 4.
Answer:
If you say 5:101 7:111 consecutive numbers and the law: one, as long as the number of the same position is not the same as the final position of the result must be 0. Second, if the high level is not the same, from the different to the lowest bit will be 0, such as 5 and 7 although the No. 0 bit is the same but because the first bit is different, so the final result No. 0 and first digit are 0.
If you understand the second rule is good to do, if another number is not the same as the final result is 0, if the number of bits is the same, from the highest bit to start looking for, will first find the difference between the lowest bit is set to 0;
In the code, by moving right until the two numbers are equal, and then moving the same number of digits to the left, the effect is to set the location to 0.
Code:
public static int Rangebitwiseand (int m, int n) {
int count=0;
while (m!=n)
{
m=m>>>1;
n=n>>>1;
count++;
}
Return m<<count;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode201 Bitwise and of Numbers Range Java