LeetCode201. Bitwise AND of Numbers Range

LeetCode201. Bitwise AND of Numbers Range

问题来源LeetCode201. Bitwise AND of Numbers Range

问题描述

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.

问题分析

返回给定的范围内所有整数位运算的结果,比如[5,7],5&6&7=4
那么这里就要分析一下这个位运算的规律了。

5&6&7=101&110&111=100
再举另外一个例子呢[5,8]
5&6&7&8=101&110&111&1000=0
这就比较明显了,这里主要看最范围内的整数二进制位数是否相同。那么假如位数相同呢,下一步就是从最高位到最低位,看每一个位是否相同,如果出现不相同,那么从这一位开始的所有位都设为0。那么这是为什么呢?

其实原理和看最高为是一样子的。比如
1111和1011,比较完第一位就剩下的111和011,也就是111和11,那么和之前的比较规则是一样子的所以说基本思路就是这样。

代码如下

Java代码

public int rangeBitwiseAnd(int m, int n) {
    // 范围出现错误或者100b和1000b这种情况进行运算
    if(m==n) return m;
    int count =0;
    int res = 0;
    while (m>0){
        if((m&1) == (n&1)){
            //如果m,n当前位是相同的
            res +=( (m&1) << count);
        }else {
            //如果m,n当前位是不同的
            res = 0;
        }
        m>>=1;n>>=1;
        count++;
    }
    if(n!=0) return 0;
    return  res;
}

可以对代码进行优化

优化的Java代码

public int rangeBitwiseAnd(int m, int n) {
    if (m == 0)
        return 0;
    int factor = 1;
    while (m != n) {
        factor <<= 1;
        m >>= 1;
        n >>= 1;
    }
    return m * factor;
}

Scala代码


object Solution201 {
  def rangeBitwiseAnd(m: Int, n: Int): Int = {

    var res = 0;

    if(m!=0){
      var mc = m;
      var nc = n;
      var facotr = 1;
      while ( mc!=nc) {
        facotr<<=1;
        nc>>=1;
        mc>>=1;
      }
      res = mc*facotr;
    }
    res
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值