Posts

Showing posts with the label Bitwise And

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. Example 1: Input: [5,7] Output: 4   Example 2: Input: [0,1] Output: 0   METHOD 1:   class Solution { public int rangeBitwiseAnd(int m, int n) { if(m == 0){ return 0; } while(n > m){ n = n & n-1; System.out.println(n); } return n; } }   Try it on Leetcode Here while we are doing BITWISE AND from n, at some point it would be less than m. And at that point whatever m we do BITWISE AND it will be n, Consider the rxample [5,7] Take 7 -> 0000 0111 (7) & 0000 0110 (6) -> 0000 0110 (6) Take 6 -> 0000 0110 (6) & 0000 0101 (5) -> 0000 0100 (4) At this point it is less than m(i.e.,5), and it exits from loop. Then return n. Consider if n at that point is doing BITWISE AND it will be again 4.  0000 01