首页 > 其他 > 详细

LeetCode:Bitwise AND of Numbers Range

时间:2016-06-12 01:59:54      阅读:142      评论:0      收藏:0      [点我收藏+]

Bitwise AND of Numbers Range




Total Accepted: 35825 Total Submissions: 115763 Difficulty: Medium

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.

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
 Bit Manipulation
















思路:

[m,n]中的所有数做“与”运算时,结果中第i位为1的条件是[m,n]中所有第i位都为1,否则为0。

因此,只需要判断m与n的最高位是否同时为1,不同时为1的话,结果为0;

同时为1时,假设这一位是第i位,这时结果为1<<i,即2^i。


java code:

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        
        int moveCount = 0;
        while(m!=n) {
            m >>= 1;
            n >>= 1;
            moveCount++;
        }
        return m <<= moveCount;
    }
}


LeetCode:Bitwise AND of Numbers Range

原文:http://blog.csdn.net/itismelzp/article/details/51637848

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