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.
1 public class Solution { 2 public int rangeBitwiseAnd(int m, int n) { 3 if(m == 0) 4 return 0; 5 int result = 0; 6 int temp = m; 7 int bits[] = new int[32]; 8 for(int i = 0; i < 32; i++){ 9 bits[i] = (temp & 1); 10 temp >>>= 1; 11 } 12 13 int carry = (n - m); 14 for(int i = 0; i < 32; i++){ 15 carry = (carry + bits[i]) / 2; 16 if(bits[i] + carry > 1) 17 bits[i] = 0; 18 } 19 20 for(int i = 31; i >=0; i--){ 21 result <<= 1; 22 result += bits[i]; 23 }//for 24 25 return result; 26 } 27 }
Please call me JiangYouDang!