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.

Analysis: The first is easy to think of, will all the numbers and operation, definitely timed out

1 classSolution {2  Public:3     intRangebitwiseand (intMintN) {4         intresult =1;5          for(inti = m; I <= N; i++) result = result &i;6         returnresult;7     }8};
View Code

Because it is a sequential integer and, the result of this bit is 0 if there is a number 0 on one bit.

If the number of n digits >m, there will be 100 ... 0 of the cases, and the result is 100 ... 00

If the number of n digits is =m, starting with the highest bit, if N and M are equal, consider the next bit until a bit is n=1,m=0 (because N>m). In this case, there will be a 100 ... 0, so the result of the and operation of the subsequent numbers is 0.

Therefore, the M and N are constantly shifted to the right, and counted against the counter until m=n.

Run time 229ms. Think about how to optimize it.

1 classSolution {2  Public:3     intRangebitwiseand (intMintN) {4         intTimes =0;5          while(M! =N) {6m = M >>1;7n = n >>1;8times++;9         }Ten         returnm<<Times ; One     } A};

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.