【LeetCode】201. Bitwise AND of Numbers Range 数字范围按位与(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
题目大意
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
解题方法
- 这题其实就是求 m 和 n 的公共前缀
- 如果最大位相等,不断往后遍历,知道相等为止
class Solution {
public int rangeBitwiseAnd(int m, int n) {
if (n / 2 >= m) return 0;
int count = 0;
while (m != n) {
m = m >> 1;
n = n >> 1;
count++;
}
return n << count;
}
}
执行耗时:7 ms,击败了54.16% 的Java用户
内存消耗:37.6 MB,击败了99.41% 的Java用户