LeetCode题号[200,299]刷题总结

时间:2020-07-12 20:03:02   收藏:0   阅读:70


201. 数字范围按位与

给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。

思路

public int rangeBitwiseAnd(int m, int n) {
    int ans = 0;
    int key = 1<<31;
    while(key != 0){
        if ((m & key) != 0 && (n & key) != 0){
            ans += key;
        } else if ((m & key) != 0 || (n & key) != 0){
            break;
        }
        key >>>= 1;
    }
    return ans;
}
public int rangeBitwiseAnd(int m, int n) {
    while (m < n){
        n &= n-1;
    }
    return m & n;
}

原文:https://www.cnblogs.com/MMMMMMMW/p/13289324.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!