zoukankan      html  css  js  c++  java
  • Bitwise AND of Numbers Range——LeetCode

    Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

    For example, given the range [5, 7], you should return 4.

    题目大意:给一个范围,返回这个范围中所有的数按位相与最后的结果。

    解题思路:当拿到这个题目的时候,我是拒绝的,这么简单的题,直接与然后返回不就是了,然后发现范围太大会TLE,后来想范围里有一个数某位是0,其他的就不用判断了,肯定是0,然后写出来这个解法,

    public int rangeBitwiseAnd(int m, int n) {
            int res = 0;
            int[] bits = new int[32];
            Set<Integer> offset = new HashSet<>();
            for (int i = 0; i < 32; i++) {
                bits[i] = 1;
            }
            out:
            for (int j = 0; j < 32; j++) {
                for (int i = m; i <= n; i++) {
                    if (bits[j] == 0)
                        break;
                    if ((i & (1 << j)) == 0) {
                        bits[j] = 0;
                        offset.add(j);
                    }
                    if (offset.size() == 32 || i == Integer.MAX_VALUE) {
                        break out;
                    }
                }
            }
            for (int i = 0; i < 32; i++) {
                res += bits[i] << i;
            }
            return res;
        }
    View Code

    结果还是TLE。

    然后看了别人的解法,更巧妙,当m!=n,那么最末位必定等0,因为[m,n]必定包含奇偶数,相与最末位等0。当m=n的时候,后面都是0,前面的就是这个范围内的数按位相与的相同部分。

    举例来说:m=4(0000 0100), n=6(0000 0110), 那么范围[4,6]中包含4、5、6,即0000 0100, 0000 0101, 0000 0110,所有的结果按位与得到0000 0100。

    初始:m!=n,于是m,n分别右移一位得到0000 0010, 0000 0011,同时偏移量offset+1;

    m!=n,于是m,n继续右移一位得到0000 0001, 0000 0001,同时偏移量offset+1;

    m=n,得到结果m<<offset。

        public int rangeBitwiseAnd(int m, int n) {
            int res = 0;
            int offset = 0;
            while(m!=n){
                m>>=1;
                n>>=1;
                offset++;
            }
            return m<<offset;
        }
  • 相关阅读:
    部门创建注意问题
    我的技术博客开通啦~
    听侯钟雷老师的讲座,确认了几个问题。
    Dynamics CRM 批量添加用户时,报错:Server was unable to process request.
    汉字的Unicode范围(转)
    转载:Apache1.1 post请求无body的bug
    转载:Android有效解决加载大图片时内存溢出的问题
    2.2之前的webkit crash问题
    转载:Expect:100Continue & HTTP 417 Expectation
    城市旅游问题
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4442193.html
Copyright © 2011-2022 走看看