Baozi Leetcode solution 201: Bitwise AND of Numbers Range

本文探讨了在给定范围内计算所有数字位与操作的两种方法:线性和对数解决方案。通过实例说明了如何找到m和n之间的公共左位,并将n右移以减少计算复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/baozitraining/p/11614656.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值