Analysis of leetcode notes in Bitwise AND of Numbers Range

Source: Internet
Author: User

Analysis of leetcode notes in Bitwise AND of Numbers Range

I. Description

Given a range[m, n]Where0 <= m <= n <= 2147483647, Return the bitwise AND of all numbers in this range, inclusive.

For example, given the range[5, 7], You shoshould return4.

Ii. Question Analysis

Given a range[m, n], Where0 <= m <= n <= 2147483647Returns the bitwise AND of All integers in the range, including the boundary.mAndn. For example, if the specified range is[5, 7], Should return4.

By looking at the description of the question, you can know that this question involves in-place operations. Therefore, you need to perform an analysis:

For the range [5, 7] given by the question, it can be written:

5: 1016: 110  -> 100 -> 47: 111

Here are two examples:

The value range is [6, 8]:

6: 01107: 0111  -> 0000 -> 08: 1000

The value range is [8, 10]:

8:  10009:  1001  -> 1000 -> 410: 1010

Now we can summarize the rule, for the range[m, n], IfnThe highest effective bit ratiomIf the maximum valid bit of is high, there will inevitably be two numbers in the range, which are the reverse codes of the other Party:

6: 01107: 0111  -> 0000 -> 08: 1000

Therefore, only whenmAndnWhen the maximum valid bits are the same, that is, m and n are shifted right at the same time, andm == n,m == 1When the bitwise AND result are not 0, the result ismAndnIn the left-side header of the public, the following provides simple code:

Iii. Sample Code

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

Iv. Summary

This is a mathematical problem that can be quickly solved using bitwise operations, mainly to find out the law.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.