Problem:
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.
Analysis:
The idea behind this problem is not hard, you could easily think out the solution. But for the implementation, you may trap yourself into some sterotypes. Idea: Since for bitwise 'AND' operation, as long as there is a '0' appears, the digit should become 0. Principle in digit change in range: (work for numerial system, binary system and other system too) Start: 1011111100111010101010 End: 1011111110001010010101 To reach 10001010010101 from 00111010101010. We must start to add 00000000000001 onto 00111010101010 => 00111010101011 ... We can we reach the '1' in high index, all digits behind after it must change once. That's to say, all the digits after 1 (include 1) should become 0. answer: 1011111110000000000000 Algorithm: Step 1: Find the first left bit 'start' differ from 'end'. Start: 10111111[0]0111010101010 End: 10111111[1]0001010010101 Step 2: Make all bits after the first different bits (include first different bit) into 0. The number is the answer we wish to get. 10111111[0]0111010101010 => 10111111000000000000 Great implementation: Move bit to reach the answer!!!! See the solution!
Solution:
public class Solution { public int rangeBitwiseAnd(int m, int n) { if (m < 0 || n < 0) throw new IllegalArgumentException("the passed in arguements is not tin the valid range!"); int p = 0; while (m != n) { m = m >> 1; n = n >> 1; p++; } return m << p; } }