Algorithm/src/main/java/bitwise/RangeBitwiseAnd.java
2025-05-23 09:17:44 +08:00

38 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package bitwise;
/**
* 题目: 201. 数字范围按位与 (rangeBitwiseAnd)
* 描述:给你两个整数 left 和 right ,表示区间 [left, right] ,返回此区间内所有数字 按位与 的结果(包含 left 、right 端点)。
*
* 你必须设计并实现线性时间复杂度的算法且使用常数级空间来解决此问题。
*
示例 1
输入left = 5, right = 7
输出4
* 链接https://leetcode.cn/problems/bitwise-and-of-numbers-range/
*/
//没看懂题目
public class RangeBitwiseAnd {
/**
* 经典做法:右移对齐再左移复原
* 令 shift = 0。
* 如果 left < right说明它们在某个更低的位上第 0~n-1 位)是不同的,需要把它们统一右移一位,并把 shift++。
* 重复步骤 2直到 left == right此时这个相等的值就是它们的公共前缀所有后面变动的位都被右移丢弃了
* 最后把 left 左移 shift 位,还原回原来数值的「高位部分」即可。
* @param left
* @param right
* @return
*/
public int rangeBitwiseAnd(int left, int right) {
int shift = 0;
// 一直右移,直到 left 和 right 对齐到公共前缀
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}
// 把对齐后的公共前缀左移回去,低位补 0
return left << shift;
}
}