LeetCode201 Bitwise and of Numbers Range Java

Source: Internet
Author: User

Topic:

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.

Answer:

If you say 5:101 7:111 consecutive numbers and the law: one, as long as the number of the same position is not the same as the final position of the result must be 0. Second, if the high level is not the same, from the different to the lowest bit will be 0, such as 5 and 7 although the No. 0 bit is the same but because the first bit is different, so the final result No. 0 and first digit are 0.

If you understand the second rule is good to do, if another number is not the same as the final result is 0, if the number of bits is the same, from the highest bit to start looking for, will first find the difference between the lowest bit is set to 0;


In the code, by moving right until the two numbers are equal, and then moving the same number of digits to the left, the effect is to set the location to 0.


Code:

public static int Rangebitwiseand (int m, int n) {

int count=0;
while (m!=n)
{
m=m>>>1;
n=n>>>1;
count++;
}
Return m<<count;



}

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

LeetCode201 Bitwise and of Numbers Range Java

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.