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.

按位做, 找到第一个n和m不相同的那一位。 那么后来的肯定都是0。(因为是从m到n连续的数字取AND, 后面的肯定有1有0)

1 public class Solution {
2     public int rangeBitwiseAnd(int m, int n) {
3         int result = 0;
4         for(int i = 31; i >= 0 && (((m >> i) & 1) == ((n >> i) & 1)); i --){
5             result |= (((m >> i) & 1) << i);
6         }
7         return result;
8     }
9 }
原文地址:https://www.cnblogs.com/reynold-lei/p/4465277.html