Bitwise_AND_of_Numbers_Range

来源:互联网 发布:宁夏国培网络研修 编辑:程序博客网 时间:2024/06/06 16:45

题目描述:

 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.
 (求m和n二进制编码中,相同的前缀 .)

思路:将两个数同时向右移位直到,两个数相同那么此时便是两个数的相同前缀,将相同的前缀恢复到原来的位置即可。
        例如5(0101)和7(0111),向右移动位数,在移动两位之后两个数的二进制均变成了(0001),最后再左移相同位数(0100)就是最后结果。

public class Bitwise_AND_of_Numbers_Range {public static int rangeBitwiseAnd(int m, int n) {        int count = 0;        while(m!=n)        {        m >>= 1;        n >>= 1;        count++;        }        return m << count;    }public static void main(String[] args) {int m = 5;int n = 7;System.out.println(rangeBitwiseAnd(m,n));}}

其中的位运算操作可以参考程序中位运算的妙用。