zoukankan      html  css  js  c++  java
  • LeetCode-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.

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

    Credits:
    Special thanks to @amrsaqr for adding this problem and creating all test cases.

     
     Analysis:
     
    Find out the largest identical part starting from left of m and n, e.g.,
    m = 20000, n=20218
    1001110| 00100000
    1001110| 10100000
    Result:
    1001110| 00000000
    Solution:
    public class Solution {
        public int rangeBitwiseAnd(int m, int n) {
            if (m>n || m==0) return 0;
            if (m==n) return m;
            
            int step =0;
            while (m!=n){
                m >>= 1;
                n >>= 1;
                step++;
            }
            return m<<=step;
            
        }
    }

    Solution 2:

    If we do not know how to perform bit operator, we can still solve it like this:

    public class Solution {
        public int rangeBitwiseAnd(int m, int n) {
            if (m>n || m==0) return 0;
            if (m==n) return m;
            
            StringBuilder mStr = new StringBuilder().append(Integer.toBinaryString(m));
            StringBuilder base = new StringBuilder();
            StringBuilder res = new StringBuilder();
            for (int i=0;i<mStr.length();i++){
                base.append('1');
                res.append('0');
            }
            
            for (int i=0;i<mStr.length();i++){
                if (mStr.charAt(i)=='0'){
                    base.setCharAt(i,'0');
                }
                if (mStr.charAt(i)=='1'){
                    int baseVal = Integer.parseInt(base.toString(),2);
                    if (n>baseVal){
                        return Integer.parseInt(res.toString(),2);
                    } else {
                        res.setCharAt(i,'1');
                    }
                }
            }
            return Integer.parseInt(res.toString(),2);
            
        }
    }
  • 相关阅读:
    VS2015编译OpenSSL1.0.2源码
    VS2015编译CURL7.54.0源码
    Mac OS Yosemite 文件批量重命名
    https 原理
    把本地仓库导入到Github
    jquery cdn加速注意事项
    关于CSS 里的_width是什么意思???
    HTML的footer置于页面最底部的方法
    html-include
    GitHub Permission to <<repository>> denied to <<username>>
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5867054.html
Copyright © 2011-2022 走看看