201. 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.
求公共的2进制前缀。
5 - 0101
7 - 0111
5到7之间的数公共的位就是 0100 -> 4
class Solution {
public:
int rangeBitwiseAnd(int m, int n)
{
int count = 0;
while ( m != n )
{
m>>=1;
n>>=1;
count++;
}
return m<<count;
}
};
本文介绍了一种算法,用于计算给定范围内所有整数的按位与运算结果。通过找到这些整数共同的二进制前缀来快速得出答案。
1525

被折叠的 条评论
为什么被折叠?



