LeetCode - Bitwise AND of Numbers Range

Bitwise AND of Numbers Range

2015.4.17 06:30

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.

Solution:

  Make it fast and simple.

Accepted code:

 1 // 1AC, easy
 2 class Solution {
 3 public:
 4     int rangeBitwiseAnd(int m, int n) {
 5         while (n > m) {
 6             n = (n & n - 1);
 7         }
 8         return m & n;
 9     }
10 };

 

你可能感兴趣的:(LeetCode)