201. Bitwise AND of Numbers Range

来源:互联网 发布:中考倒计时软件下载 编辑:程序博客网 时间:2024/05/29 17:26

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.

如果m, n不同,那么肯定包含一个奇数一个偶数,那么最后一位变成0,如果m的最高位跟n的最高位没在同一位,最后结果位0。代码如下:

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

原创粉丝点击