Bitwise AND of Numbers Range -- LeetCode, leetcode

Source: Internet
Author: User

Bitwise AND of Numbers Range -- LeetCode, leetcode

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

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

Train of Thought: the first train of thought must start with bitwise AND from the first number, but the complexity is too high and new improvements are made. If there is a power of 2 in this range, from this point on, the power of the 2 is equal to n. If the power of the 2 is smaller than m, the installation or installation will start from this range.

int rangeBitwiseAnd(int m, int n) {int i;int result ;for(i=0;;i++)if(pow(2,i)>n)break;if(pow(2,i-1) < m){result = m;for(i=m+1;i<=n;i++) result  &= i; }   else{result = pow(2,i-1);i = pow(2,i-1)+1;for(;i<=n;i++) result &= i;}     return result;} 

Looking at other people's code, we can find that there is a faster speed. For a continuous digital sequence, the last two adjacent numbers must be different, so as long as m! = N, then the last digit must be 0, so we can see from which one starts m = n.

int rangeBitwiseAnd(int m, int n) {          int offset = 0;          while (m && n)          {              if (m == n)              {                  return m << offset;              }              m >>= 1;              n >>= 1;              offset++;          }            return 0;      }  


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.