Baozi Leetcode solution 201: Bitwise AND of Numbers Range
Posted baozitraining
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Baozi Leetcode solution 201: Bitwise AND of Numbers Range相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
Baozi Leetcode solution 135: Candy
Baozi Leetcode solution 72. Edit Distance
Baozi Leetcode solution 229: Major Element II
Baozi Leetcode solution 201: Bitwise AND of Numbers Range
Baozi Leetcode solution 1292. Maximum Side Length of a Square with Sum Less than or Equal to Th