前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 201 Bitwise AND of Numbers Range

Leetcode 201 Bitwise AND of Numbers Range

作者头像
triplebee
发布2018-01-12 14:46:59
4410
发布2018-01-12 14:46:59
举报
文章被收录于专栏:计算机视觉与深度学习基础

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.

统计区间内的数位与的结果。

只要m!=n,那么他们之间至少存在一个奇数一个偶数,这两个数与最后一位肯定为0,

如果m == n,那么只有一个数,结果为这个数本身。

这样可以逐位进行比较。

代码语言:javascript
复制
class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        if(m == 0) return 0;
        int res = 1;
        while(m != n)
        {
            m >>= 1;
            n >>= 1;
            res <<= 1;
        }
        return m * res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-03-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档