201Bitwise AND of Numbers Range

来源:互联网 发布:linux应用领域 编辑:程序博客网 时间:2024/05/29 10:07

题目链接: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.For example, given the range [5, 7], you should return 4.

解题思路:
这题的考点是 bit 操作
这题的思路可以借鉴191 Number of 1 Bits。
在《剑指offer》中,提供一种思路。n & (n - 1) 可以将 n 最右一个 1 变为 0.
例如:1100 -> 1100 & 1011 -> 1000
对本题来说:
1. 对按位与运算结果的每一位来说,只要 m 和 n 之间的数在该位为 0,那么该位做与运算后肯定为 0。
2. 当 n > m 时,m 和 n 之间的数总在低位存在 0。通过不断地将 n 最右一个 1 变为 0,使 n 逐渐靠近 m,使 m 和 n 尽可能在高位上取得一致,或者 m 直接为 0。
3. 当 n <= m 时,n 已最大限度靠近 m,此时的 n 为所求得结果。

代码实现:

public class Solution {    public int rangeBitwiseAnd(int m, int n) {         while (n > m) {              n = n & (n - 1);//消去 n 最右一个 1,使其变为 0         }         return n;    }}
8266 / 8266 test cases passed.Status: AcceptedRuntime: 9 ms
0 0
原创粉丝点击