您的位置:首页 > 其它

Bitwise AND of Numbers Range

2015-09-09 04:39 246 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: