LeetCode-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.

 

题目大意

给一个区间[m, n],求该区间内所有元素按位and的结果。

 

示例

E1

Input: [5,7]
Output: 4

E2

Input: [0,1]
Output: 0

 

解题思路

根据and的特性,有0时该数位永远为0,不论有多少个1。

因此按位计算,若m与n不等则表示该数位最后一位一定为0,如果m与n相等,则表示m与n剩余数位部分即为剩下数位的答案。

若m与n之间的差值过大,则从m到n之间所有数字的and的结果一定为0 。

 

复杂度分析

时间复杂度:O(1)

空间复杂度:O(1)

 

代码

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        long res = 0, k = 1;
        //对m,n的每个数位进行比较
        while(m && n) {
            //若m与n相等,则将最后一个数位的结果加到结果中
            if(!(n - m)) {
                if(m & 1)
                    res += k;
            }
            //若m与n不等,则继续
            k <<= 1;
            m >>= 1;
            n >>= 1;
        }
        //如果m与n之差大于一个2的数位,则所有数位都应为0
        if(m || n)
            res = 0;
        
        return res;
    }
};
posted @ 2019-06-10 11:24  你好哇傻小妞  阅读(105)  评论(0编辑  收藏  举报