Bitwise AND of Numbers Range

实现范围内的按位与

思路:首先将m与n做按位与得到tmp。对于tmp中为0的位,则最终结果也一定为0;对于tmp中为1的位,则要看m到n中间有没有数的这一位为0,方法是:将m的这一位及其低位全部置1得到数a,如果a<n,则说明m到n中间存在这一位为0的数。

 1 public class Solution {
 2     public int rangeBitwiseAnd(int m, int n) {
 3         int res = m & n;
 4         
 5         for (int j = 0; j < 31; j++) {
 6             if ((res & (1 << j)) != 0) {       //如果第j位为0
 7                 int a = 1 << (j + 1);
 8                 a--;
 9                 if ((a | m) < n) {
10                     res &= (~(1 << j)); 
11                 }
12             }
13         }
14         return res;
15     }
16 }
View Code

相关文章:

  • 2022-12-23
  • 2022-02-09
  • 2022-03-04
  • 2021-08-11
  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
猜你喜欢
  • 2021-09-10
  • 2021-05-31
  • 2021-07-26
  • 2021-08-15
  • 2021-12-11
  • 2021-10-15
  • 2022-12-23
相关资源
相似解决方案