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.this

For example, given the range [5, 7], you should return 4.spa

 

 

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

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 }
相关文章
相关标签/搜索