[Leetcode] Bitwise and of Numbers Range (bitwise operations)

Source: Internet
Author: User

It has to be said that the application of bit arithmetic is very ingenious.

This problem asks for a continuous interval integer and the value of the operation, the breakout point lies in the continuous interval of this feature. We can find a few numbers to see the rules,

2 3 4 5 binary is 10, 11,100,101, can be found if m==n, then M is the answer; when M!=n, because of the continuous two number of binary

The last one is certainly not the same, with the value must be 0, the previous same section (1&1=1,0&0=0) remains.

So each time we first judge, different words will move right one, compare the previous, until the same time end, the last left to move the number of digits.

There is no need to worry about 1 of the time left shift will cause overflow, and thus fail, because the right shift is preceded by 0.

Class Solution {public:    int rangebitwiseand (int m, int n) {        int res = 0;        int offset = 0;        while (m!=n) {            m>>=1;            n>>=1;            offset++;        }        Return m<<offset;    }};


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Leetcode] Bitwise and of Numbers Range (bitwise operations)

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.