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

LeetCode:Bitwise AND of Numbers Range

时间:2016-06-12 02:00:20      阅读:113      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!