[Leetcode] Bitwise and of Numbers Range

Source: Internet
Author: User
Tags bitwise

Bitwise and of Numbers Range

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.

Special thanks to @amrsaqr for adding this problem and creating all test cases.

Has you met this question in a real interview? Idea: Find the law can, through analysis we found: 1, when m = N, directly return m or N. 2, when the length of the binary number representing m and n is unequal, the number of occurrences is bound to be 100 because the lower one is like a high one. 0, the length is a bit longer than the low number, this number and the length of the number is smaller than its "with", the result must be 0, 0 "and" any number is 0. That is, when the length of the binary number that represents m,n is inconsistent, the "and" operation is performed from M to N, the result is 0, and 3, when the length of the two is the same, the loop and operation can be done. Just note: When N is Int_max, special handling is required.
classsolution{ Public:  intRangebitwiseand (intMintN) {intRET =m; intA = m, B =N; intLena =1, LenB =1; if(M = =N)returnm;  while(A >>=1) Lena++;  while(b >>=1) LenB++; if(Lena = =LenB) {       for(inti = m +1; I <= N; i++) {ret&=i; if(i = =Int_max) Break; }    }    Elseret=0; returnret; }};

[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.