LeetCode: 201. Bitwise AND of Numbers Range

LeetCode: 201. 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 = AX, n=AY,则, mn 的所有数字高位都是 A。而 XY 的最高位(由于 m <= n) 分别是 0, 1。 因此,mn 的低位中, XY 的所有数字都出现了,这些数按位相与为 0m&(m-1)...(n-1)n = AO(其中,O为低位的 0)。

AC 代码

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int cnt = 0;

        while(m != n) 
        {
            m >>= 1;
            n >>= 1;
            ++cnt;
        }

        return (m << cnt);
    }
};
全部评论

相关推荐

02-14 12:40
门头沟学院 Java
程序员花海:1.面试要求必须Java笔试不一定 2.难度对等秋招 远超于日常实习是因为同一批次且转正很多 竞争压力大 3.第一个加点指标,上线了就把接口性能加上去 使用本地缓存这个不算亮点 只是技术选型,要把为什么采用这个和背后的思考写出来而不是单纯堆叠技术没意义 4.八股要一直看 很容易忘记 5.拼团交易这个老问题 堆积技术 另外建议你把奖项合并到教育背景 没必要拆出来放最后
我的简历长这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务