前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#版 - Leetcode 201. 数字范围按位与(bitwise AND) - 题解

C#版 - Leetcode 201. 数字范围按位与(bitwise AND) - 题解

作者头像
Enjoy233
发布2019-03-05 15:37:53
6020
发布2019-03-05 15:37:53
举报

C#版 - Leetcode 201. 数字范围按位与(bitwise AND) - 题解

在线提交: https://leetcode.com/problems/bitwise-and-of-numbers-range/

题目描述

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

示例 1:

代码语言:javascript
复制
输入: [5,7]
输出: 4

示例 2:

代码语言:javascript
复制
输入: [0,1]
输出: 0

  • 题目难度:Medium
  • 通过次数:139
  • 提交次数:449
  • 贡献者:amrsaqr
  • 相关话题 位运算

思路: 两个数按位与的结果为相同的部分保持不变,不相同的部分会被置为零,多个数的按位与的结果与之类似。 根据按位与的性质可知,如果数字m != n,则在m, n范围内的数的最后一位必然同时存在1和0,因此最后一位的按位与&的结果必为0。而如果m=0,所有数按位与的结果必然为0。

举例而言:

例1. [9, 11],其范围内的数字的二进制表示依次为:

1 001

1 010

1 011

这些数按位相与后的结果为1 000。

例2.[20, 23],其范围内的数字的二进制表示依次为:

101 00

101 11

这些数按位相与后的结果为101 00。

例3.[4, 23],其范围内的数字的二进制表示依次为:

00100

10111

这些数按位相与后的结果为00000,因为高位没有共同字符串。

因此,m,n范围内的数的按位与的结果就是各个数的各位对齐后高位共同数字串末尾全补0的值。

已AC代码:

代码语言:javascript
复制
public class Solution
{
    public int RangeBitwiseAnd(int m, int n)
    {
        // 题中规定数据范围: m, n中较大值<=31s = 2147483647
        int shiftCount = 0;
        int common = 0;
        GetCommonDigits(m, n, ref common, ref shiftCount);
        var res = common << shiftCount;  // 末位补0

        return res;
    }

    public void GetCommonDigits(int a, int b, ref int common, ref int shiftCount)
    {
        shiftCount = 0;
        while (a != b)
        {
            a = a >> 1;
            b = b >> 1;
            shiftCount++;
        }
        common = a;
    }
}

当然也可使用递归解法:

代码语言:javascript
复制
public static int RangeBitwiseAnd(int m, int n)
{
    if (m < n)
        return (RangeBitwiseAnd(m >> 1, n >> 1) << 1);
    else return m;
}

Rank:

You are here! Your runtime beats 96.88% of csharp submissions.

Refrence: https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/56789/C-Solution-with-bit-shifting-(Beats-90)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年06月10日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C#版 - Leetcode 201. 数字范围按位与(bitwise AND) - 题解
    • 题目描述
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档