前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 201 Bitwise AND of Numbers Range

LeetCode 201 Bitwise AND of Numbers Range

原创
作者头像
大学里的混子
修改2018-10-29 17:11:21
2480
修改2018-10-29 17:11:21
举报
文章被收录于专栏:LeetCode

201 Bitwise AND of Numbers Range

The hardest part of this problem is to find the regular pattern. For example, for number 26 to 30 Their binary form are: 11010 11011 11100 11101 11110

Because we are trying to find bitwise AND, so if any bit there are at least one 0 and one 1, it always 0. In this case, it is11000. So we are go to cut all these bit that they are different. In this case we cut the right 3 bit.

I think after understand this, the code is trivial:

代码语言:java
复制
    public int rangeBitwiseAnd(int m, int n) {
      int i = 0; // i means we have how many bits are 0 on the right
      while(m != n){
        m >>= 1;
        n >>= 1;
        i++;  
      }  
      return m << i;  
    }

解法说明:就是将头尾两个数据都向右移动,直到二者相等为止。然后后面的都补零。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 201 Bitwise AND of Numbers Range
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档