Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/#Bitwise AND of Numbers Range.md
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
40 lines (34 sloc)
960 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. | |
Example 1: | |
Input: [5,7] | |
Output: 4 | |
Example 2: | |
Input: [0,1] | |
Output: 0 | |
``` | |
My code: | |
```python | |
class Solution(object): | |
def rangeBitwiseAnd(self, m, n): | |
""" | |
:type m: int | |
:type n: int | |
:rtype: int | |
""" | |
if m.bit_length() > n.bit_length(): | |
return 0 | |
size = (m ^ n).bit_length() | |
return n & (~((1 << size)-1)) | |
#1<<size get the bit_length of and operation | |
#~ operation for Complement operation | |
def rangeBitwiseAnd2(self, m, n): | |
if not m or not n or m==n: | |
return m&n | |
lm,ln = int(math.log(m,2)),int(math.log(n,2)) | |
if lm != ln: | |
return 0 | |
return 2**lm + self.rangeBitwiseAnd(m%(2**lm),n%(2**ln)) | |
``` | |
Solution: | |
https://leetcode.com/problems/bitwise-and-of-numbers-range/ |