加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

LeetCode 201. 数字范围按位与(Bitwise AND of Numbers Range)

发布时间:2020-12-14 04:45:25 所属栏目:大数据 来源:网络整理
导读:201. 数字范围按位与 201. Bitwise AND of Numbers Range 题目描述 给定范围 [m,n],其中 0 = m = n = 2147483647,返回此范围内所有数字的按位与(包含 m,n 两端点)。 LeetCode 201. Bitwise AND of Numbers Range 中等 示例 1: 输入: [5,7] 输出: 4 示例

201. 数字范围按位与
201. Bitwise AND of Numbers Range

题目描述
给定范围 [m,n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m,n 两端点)。

LeetCode201. Bitwise AND of Numbers Range中等

示例 1:

输入: [5,7]
输出: 4

示例 2:

输入: [0,1]
输出: 0

Java 实现
方法一

class Solution {
    public int rangeBitwiseAnd(int m,int n) {
        int d = Integer.MAX_VALUE;
        while ((m & d) != (n & d)) {
            d <<= 1;
        }
        return m & d;
    }
}

方法二

class Solution {
    public int rangeBitwiseAnd(int m,int n) {
        int count = 0;
        while (m != n) {
            m >>= 1;
            n >>= 1;
            count++;
        }
        return m << count;
    }
}

参考资料

  • https://leetcode.com/problems/bitwise-and-of-numbers-range/
  • https://www.cnblogs.com/grandyang/p/4431646.html
  • https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读