201. Bitwise AND of Numbers Range

来源:互联网 发布:java编写计算器的源码 编辑:程序博客网 时间:2024/05/29 17: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.

m,n同时向右移位直到m和n相等,用k记录移了多少位,然后返回现在的m向左移k位得到的数。因为m和n之间的数按位与,得到的数后k位肯定为0。

class Solution {public:    int rangeBitwiseAnd(int m, int n)     {        int k=0;        while(m!=n)        {            m>>=1;            n>>=1;            k++;        }        return m<<k;    }};
0 0
原创粉丝点击