码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 201. Bitwise AND of Numbers Range(位运算,dp)

时间:2016-04-25 06:41:47      阅读:103      评论: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.

题解:如果m==n,那么答案就是m.

如果m<n,那么二进制最右边一位在最后的结果中肯定是0,那么就可以转化成子问题:

rangeBitwiseAnd(m>>1, n>>1)

 

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        return (n > m) ? (rangeBitwiseAnd(m>>1, n>>1) << 1) : m;
    }
};

 

leetcode 201. Bitwise AND of Numbers Range(位运算,dp)

标签:

原文地址:http://www.cnblogs.com/zywscq/p/5429171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!