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