201.Bitwise AND of Numbers Range

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.

思路:我们先以[26,30]为例,有:

11010 11011 11100 11101 11110

可见最后求得的结果是范围内所有的数公共的二进制前缀,即最终求得是最长公共二进制前缀。我们可以每次将m和n右移一位,直至m,n相等,同时记录向右移动的次数i,此时m就是我们要求的公共二进制前缀右移i位得到的数,将m左移i位即可求得最终结果。

  1. class Solution {
    public:
        int rangeBitwiseAnd(int m, int n) {
            int offset=0;
            while(m!=n){
                m>>=1;
                n>>=1;
                offset++;
            }
            return m<<offset;
        }
    };



原文地址:https://www.cnblogs.com/zhoudayang/p/5039530.html