[Leetcode]201.bitwise and of Numbers Range

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.

Ideas

[5, 7] A total of three numbers (5,6,7), the binary is:

1 1 1 11

The result is 100 after the phase

[9, 11] A total of three numbers (9,10,11), the binary is:

1 001 1 010 1 011

The result is 1000 after the phase

[26, 30] a total of five numbers (26,27,28,29,30), the binary is:

one 010 one 011 each 101 110

The result is 11000 after the phase

Looking closely we can conclude that the result we are asking for is the part of the left public 1 of all the numbers in the given range, and the other bits are 0.

Code

/ *---------------------------------------* Date: 2015-04-26* sjf0115* title: 201.Bitwise and of Numbers range* website: HT   tps://leetcode.com/problems/bitwise-and-of-numbers-range/* Result: ac* Source: leetcode* Blog:-----------------------------------------* *#include <iostream>#include <vector>#include <algorithm>using namespace STD;classSolution { Public:intRangebitwiseand (intMintN) {if(M = =0){return 0; }//if        intCount =0; while(M! = N) {//Move left oneM >>=1; N >>=1;        ++count; }//while        returnM << count; }};intMain () {solution solution;intm =9;intn = One;intresult = Solution.rangebitwiseand (m,n);//Output    cout<<result<<endl;return 0;}

Run time

[Leetcode]201.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.