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;
        }
    }
  • 相关阅读:
    有用网站
    html5页面布局总结
    video和audio支持格式
    关于浏览器缓冲
    java常见面试题汇总
    jvm常用相关参数
    规律字符串拼接
    线程基础知识
    Kafka学习
    Redis学习
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6612333.html
Copyright © 2011-2022 走看看