码迷,mamicode.com
首页 > 其他好文 > 详细

Baozi Leetcode solution 201: Bitwise AND of Numbers Range

时间:2019-10-01 09:39:23      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:www   discuss   comm   linear   tput   div   while   color   VID   

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

 

 1 public int rangeBitwiseAnd(int m, int n) {
 2     // avoid overflow
 3     long res = m;
 4 
 5     for (long i = (long)m + 1; i <= (long)n; i++) {
 6         res = res & i;
 7         if (res == 0) return 0;
 8     }
 9 
10     return (int)res;
11 }

 

Time Complexity: O(N) essentially n - m

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

 

Logarithmic solution

 1 public int rangeBitwiseAnd(int m, int n) {
 2     if (n == m) {
 3         return n;
 4     }
 5     int digit = 0;
 6     while (m != n) {
 7         m >>= 1;
 8         n >>= 1;
 9         digit++;
10     }
11 
12     return m << digit;
13 }

 

 

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

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

 

References

Baozi Leetcode solution 201: Bitwise AND of Numbers Range

标签:www   discuss   comm   linear   tput   div   while   color   VID   

原文地址:https://www.cnblogs.com/baozitraining/p/11614656.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!