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 };

 

 posted on 2015-04-17 06:32  zhuli19901106  阅读(391)  评论(0编辑  收藏  举报