"201-bitwise and of Numbers range (range digits and results)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
code Download "Https://github.com/Wang-Jun-Chao"
Original Question
Given a range [M, n] where 0 <= m <= n <= 2147483647
, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7]
, you should return 4
.
Main Topic
Gives a range that returns all the numbers in this range as a bitwise and the final result.
Thinking of solving problems
When M!=n, then the lowest last must wait for 0, because [M, n] must contain the odd even, and the first 0. M,n can be moved to the right one bit, as MK, NK, this is equivalent to the [M, n] All the number between the right moved a bit, when the mk=nk, stating that before [M, n] The number between the right one after the other is equal, the number after the right shift for and operation, the result is M (=n), So the operation can stop the number of records right SHIFT, Offset,m>>offset is the result
Code Implementation
Algorithm implementation class
publicclass Solution { publicintrangeBitwiseAnd(intint n) { int0; while (m != n) { 1; 1; offset++; } return m << offset; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47997613"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "201-bitwise and of Numbers range (range digits and results)"