Leetcode 201 Bitwise AND of Numbers Range

来源:互联网 发布:做微信淘客用什么软件 编辑:程序博客网 时间:2024/06/05 09:33

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,那么只有一个数,结果为这个数本身。

这样可以逐位进行比较。

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


1 0
原创粉丝点击