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.

Example 1:

Input: [5,7]
Output: 4

Example 2:

Input: [0,1]
Output: 0

题源:here

感悟:第一次在线编程,感觉确实需要对数据有非常深的理解才可以啊。

思路:

第一种方法误打误撞竟然还通过测试了:

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int range = n-m;
        for(int i = 0;range;range/=2, i++){
            m &= ~(1<<i);
        }
        m &= n;
        return m;
    }
};

这种方法应该是首创吧。。。我首先是认为只要m到n的过程中,有的位出现了变化,那么这些位置肯定就是0了,最后m和n再与一下是为了排除m到n进位的情况。

第二种方法是参考了:here

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        return n>m?(rangeBitwiseAnd(m/2,n/2)<<1):m;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值