• 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;
        }
    };
  • 相关阅读:
    Leetcode Binary Tree Preorder Traversal
    Leetcode Minimum Depth of Binary Tree
    Leetcode 148. Sort List
    Leetcode 61. Rotate List
    Leetcode 86. Partition List
    Leetcode 21. Merge Two Sorted Lists
    Leetcode 143. Reorder List
    J2EE项目应用开发过程中的易错点
    JNDI初认识
    奔腾的代码
  • 原文地址:https://www.cnblogs.com/heyn1/p/10996717.html
Copyright © 2020-2023  润新知