LeetCode201. Bitwise AND of Numbers Range

来源:互联网 发布:如何清理淘宝缓存 编辑:程序博客网 时间:2024/05/20 02:54

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  }}
原创粉丝点击