Every day a leetcode-----calculates the results of all the numbers in a given range

Source: Internet
Author: User
Tags bitwise
Bitwise and of Numbers Range

Original title link bitwise AND of Numbers Range

Calculating the results of all numbers in the range of [m:n] [m:n] [m:n]

First you need to clarify a few knowledge points a& (a+1) A & (A + 1) a \& (A + 1) the lowest bit must be 0 0&b 0 & B 0 \& b The result must be 0 a& (a+1) & (A + 2) &...& (A+k) A & (A + 1) & (A + 2) & ... & (A + K) a \& (A + 1) \& (A + 2) \& The lowest bit of \& (A + K) must be 0.

So if n > m, then [M:N] [m:n] [m:n] in the range of all elements and the lowest bit of the result of the operation must be 0, so there is

All_nums_and (m, n) = All_nums_and (M >> 1, n >> 1) << 1

Where All_nums_and (M, n) represents the result of all the elements in the range [m:n] [m:n] [m:n]

The code is as follows

Class Solution {public
:
    int rangebitwiseand (int m, int n) {
        return n <= m? M:rangebitwiseand (M >> 1, n >> 1) << 1;  
    }
};
Related Article

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.