Bitwise AND of Numbers Range

来源:互联网 发布:路由器网速控制软件 编辑:程序博客网 时间:2024/05/10 11:18

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.

public int rangeBitwiseAnd(int m, int n) {        if(m == 0){            return 0;        }        int moveFactor = 1;        while(m != n){        //m,n都向右移动一位,直到m=n为止            m >>= 1;            n >>= 1;            //factor向左移动一位,右边补零            moveFactor <<= 1;        }        //两者相乘就是结果        return m * moveFactor;    }    /**     * e.g:[125,127]     * 1111101  ==> 125     * 1111110  ==> 126     * -------     * 1111100     * 1111111  ==> 127     * -------     * 1111100  ==>124     *      * 1111100 = 11111     * *   100     * -------     * 1111100     */
http://www.zybang.com/question/06d40cb634d7cbf93a3b4f951d6fa9f7.html

0 0