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

201. Bitwise AND of Numbers Range

发布时间:2020-12-14 05:18:33 所属栏目:大数据 来源:网络整理
导读:https://leetcode.com/problems/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:

https://leetcode.com/problems/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

解题思路:

先硬来,超时。

看大神的解法,结论是这道题其实就是要找m和n的bit common prefix。而不需要从m一直算到n。

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

https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/56729/Bit-operation-solution(JAVA)

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

(编辑:李大同)

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

    推荐文章
      热点阅读