[leetcode] 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.

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

Show Tags
 
[Solution]
只需求出m和n的最高位相同位置,然后后续位置置零即可。
 1 int rangeBitwiseAnd(int m, int n) 
 2 {
 3     int count = 0;
 4     while (m != n)
 5     {
 6         m >>= 1;
 7         n >>= 1;
 8         count++;
 9     }
10     
11     return (m << count);
12 }

 

你可能感兴趣的:([leetcode] 201. Bitwise AND of Numbers Range)