[Leetcode] 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.
总结规律
10110 0101 = m
10110 0110
10110 0111
10110 1000
10110 1001
10110 1010
10110 1011 = n
发现上面数字的高位的5位是相同的,第四位是不同而,我们如何找到这高五位?下面是两种实现方法。
1 public class Solution { 2 private int solution1(int m,int n){ 3 int bitxor = 1; 4 //如果当前两个数字不相等,那么就将两个数的最低位当前最低位清零。 5 while(m!=n){ 6 int tmp = m & bitxor; 7 if(tmp != 0) 8 m = m ^ bitxor; 9 tmp = n & bitxor; 10 if(tmp!=0) 11 n = n ^ bitxor; 12 bitxor = bitxor << 1; 13 } 14 return n; 15 } 16 private int solution2(int m,int n){ 17 int order = 0; 18 while(m!=n){ 19 m = m >> 1; 20 n = n >> 1; 21 order++; 22 } 23 return m<<order; 24 } 25 public int rangeBitwiseAnd(int m, int n) { 26 return solution2(m,n); 27 } 28 }