201. Bitwise AND of Numbers Range

来源:互联网 发布:剑灵免费捏脸数据大全 编辑:程序博客网 时间:2024/05/29 09:57

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之间的数字按位与操作。
如果两个数的位数不同,则一定为0;若位数相同,则看m和n右边有多少位是不同的,若不同,则一定有0,那么and操作出来的就是0。

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