### Problem Statement

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

Problem link

### Video Tutorial

You can find the detailed video tutorial here### Thought Process

Normally we just implement as we do at work, which is keep increasing the number and do an AND. It will still pass the OJ, just need to pay attention to overflow situation (using a long would solve the problem)Now we are pushing ourselves, can we solve it more than linear. Only log/binary is faster than linear. The idea is to find the common left bits of m and n, and later shift n (total number of digits - common length digits) because the right part would end up to be 0.

For example, from 4 to 7, thte common left part is 1, the range and value would be 100 (which is n left shift twice)

- 1 00
- 1 01
- 1 10
- 1 11

### Solutions

#### Linear solution

Time Complexity: O(N) essentially n - m

Space Complexity: O(1) no extra space is needed

#### Logarithmic solution

Time Complexity: O(lgN) because we keep dividing 2 (left shift) of n

Space Complexity: O(1) no extra space is needed

## No comments:

## Post a Comment