首页 > 其他 > 详细

【leetcode】Bitwise AND of Numbers Range(middle)

时间:2015-04-16 23:16:27      阅读:193      评论: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.

 

思路:

先找前面二进制相同的位,后面不相同的位相与一定为0. 

比如: 1111001

         1110011

从0011 - 1001 中间一定会经过 1000 从而使这四位都为0

我的代码:

int rangeBitwiseAnd(int m, int n) {
        int ans = 0;
        int t = 30;
        while(t >= 0 && ((m & (1 << t)) == (n & (1 << t))))
        {
            ans |= m & (1 << t);
            t--;
        }
        return ans;
    }

 

别人的代码:更精简

int rangeBitwiseAnd(int m, int n) {
    int r=Integer.MAX_VALUE;
    while((m&r)!=(n&r))  r=r<<1;
    return n&r;
}

 

【leetcode】Bitwise AND of Numbers Range(middle)

原文:http://www.cnblogs.com/dplearning/p/4433530.html

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