Leetcode Bitwise and of Numbers Range

Source: Internet
Author: User

Given a range [M, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, Inclus Ive.

For example, given the range [5, 7], and you should return 4.

This is a bit operation.

One basic formula to explore is (N & (n-1))

Suppose there is such a number xxxxxxxxxxx10000 (this indicates that the rightmost one is a bit of 1, and X is 1 can be 0)

So n-1 = xxxxxxxxxxx01111

N & (n-1)?

We found that the 1 right side was eliminated.

Wait, there seems to be information to explore n = xxxxxxxxxxx10000, n-1 = xxxxxxxxxxx01111, N & (n-1) = xxxxxxxxxxx00000

Have you found that the difference between N and (N & (n-1)) is not more than 1 ah, so what is the number of this between the form??

n = xxxxxxxxxxx10000

N-1 = xxxxxxxxxxx01111

xxxxxxxxxxx01110

......

Xxxxxxxxxxx0xxxx

......

N & (n-1) = xxxxxxxxxxx00000

Did you find out that all these numbers and the result is N & (n-1)

So the solution is very concise:

    int Rangebitwiseand (int m, int n) {        while (n > M)            n &= n-1;        return n;    }

Leetcode Bitwise and of Numbers Range

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.