Bitwise AND of Numbers Range
Total Accepted: 35825
Total Submissions: 115763
Difficulty: Medium
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.
Subscribe to see which companies asked this question
思路:
[m,n]中的所有数做“与”运算时,结果中第i位为1的条件是[m,n]中所有第i位都为1,否则为0。
因此,只需要判断m与n的最高位是否同时为1,不同时为1的话,结果为0;
同时为1时,假设这一位是第i位,这时结果为1<<i,即2^i。
java code:
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int moveCount = 0;
while(m!=n) {
m >>= 1;
n >>= 1;
moveCount++;
}
return m <<= moveCount;
}
}