【leetcode】201. 数字范围按位与【先转化;然后是一道数学题目】

在这里插入图片描述

先转化问题,就是求出 m和n两个数字的公共二进制前缀是多少。

可以利用 n&(n-1) 去除最右面的1来求出结果。

在这里插入图片描述

class Solution {
    
    
    public int rangeBitwiseAnd(int m, int n) {
    
    
        // 思路是 找到 m 和 n 的公共前缀。就是结果。
        // 方法一:同时右移,直到相等。然后恢复。
        // 方法二:利用 n&(n-1) 能够 去除 最右位的 1,处理n,直到n<=m 就是结果。
        /*用方法二来解题*/
        while (n > m) {
    
    
            n &= (n - 1);
        }
        return n;
    }
}

猜你喜欢

转载自blog.csdn.net/Mason97/article/details/108179511
今日推荐