201 Bitwise AND of Numbers Range

题目链接: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: Accepted
Runtime: 9 ms
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值