Skip to content

Latest commit

 

History

History
43 lines (27 loc) · 1.03 KB

201-bitwise-and-of-numbers-range.md

File metadata and controls

43 lines (27 loc) · 1.03 KB

201. Bitwise AND of Numbers Range - 数字范围按位与

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

示例 1: 

输入: [5,7]
输出: 4

示例 2:

输入: [0,1]
输出: 0

题目标签:Bit Manipulation

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
java 4 ms 34.1 MB
class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        // n & (n - 1) 可以把最右的1变为0
        while (n > m) {
            n &= (n - 1);
        }
        return n;
    }
}