首页 > 其他 > 详细

[LeetCode] Bitwise AND of Numbers Range

时间:2015-04-29 19:47:41      阅读:170      评论:0      收藏:0      [点我收藏+]

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.

解题思路

① n&(n-1),可以去除n的最低位的1。
② 从n一直与到m,可以去掉的1就是n和m的右端不相等的部分的1。
例如对于如下m和n:
110100111101 –>m
110111111111 –>n
可以去掉的就是n的红色部分的1。

实现代码

//Runtime:100ms
class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        char bit = 0;
        while (m != n)
        {
            m >>= 1;
            n >>= 1;
            bit++;
        }

        return m << bit;
    }
};

[LeetCode] Bitwise AND of Numbers Range

原文:http://blog.csdn.net/foreverling/article/details/45370263

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!