zoukankan      html  css  js  c++  java
  • leetcode 201. Bitwise AND of Numbers Range 求范围中,每一位都是1的数 ---------- java

    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.

    1、首先换成2进制,如果长度不一样,那么一定是0.

    然后从较大的位置开始判断,如果均为1,那么该位置为1,均为0,判断下一位,如果不一样,那么就返回结果。

    public class Solution {
        public int rangeBitwiseAnd(int m, int n) {
            int len1 = getLen(m);
            int len2 = getLen(n);
            if (len1 != len2 || m == 0){
                return 0;
            }
            int result = (1 << (len1 - 1));
            for (int i = len1 - 2; i >= 0; i--){
                if (((m >> i) & 1) == 1 && ((n >> i) & 1) == 1){
                    result += (1 << i);
                } else if (((m >> i) & 1) == 0 && ((n >> i) & 1) == 0){
                    continue;
                } else {
                    return result;
                }
            }
            return result;
        }
        public int getLen(int n){
            int result = 0;
            while (n != 0){
                result++;
                n /= 2;
            }
            return result;
        }
    }

    2、参考discuss,发现更简单的做法= =。虽然代码更少,但是判断次数应该是比第一重要多的。

    public class Solution {
        public int rangeBitwiseAnd(int m, int n) {
            int i = 0;
            for (; m != n; ++i) {
                m >>= 1;
                n >>= 1;
            }
            return n << i;
        }
    }
  • 相关阅读:
    [BJOI2006]狼抓兔子
    [HNOI2016]最小公倍数
    hihocoder 1419 重复旋律4
    [NOI2015]品酒大会
    [SDOI2016]生成魔咒
    [ZJOI2009]狼和羊的故事
    BZOJ4361 isn
    [SDOI2009]虔诚的墓主人
    BZOJ 3329 Xorequ
    [ZJOI2013]丽洁体
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6612333.html
Copyright © 2011-2022 走看看