Skip to content

Commit

Permalink
Create 201._Bitwise_AND_of_Numbers_Range.md
Browse files Browse the repository at this point in the history
  • Loading branch information
0xkookoo authored Sep 16, 2018
1 parent ab28919 commit 885c007
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions docs/Leetcode_Solutions/201._Bitwise_AND_of_Numbers_Range.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# 201. Bitwise AND of Numbers Range

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接
* https://leetcode.com/problems/bitwise-and-of-numbers-range/description/

> 内容描述
```
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
```

## 解题方案

> 思路 1
******- 时间复杂度: O(1)******- 空间复杂度: O(1)******

我们知道你从m一直&到n,那么m和n二进制位后面不一样的地方肯定都会变成0

所以我们找到m和n的最长相同前缀,然后补齐二进制的32位(即往右边贴'0')

自己写的一行版本!


```python
import os
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
return int(os.path.commonprefix([bin(m)[2:].zfill(32), bin(n)[2:].zfill(32)])[::-1].zfill(32)[::-1], 2)
```


> 思路 2
******- 时间复杂度: O(1)******- 空间复杂度: O(1)******


别人的一行版本!


```python
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
return self.rangeBitwiseAnd(m, n & n-1) if m < n else n
```

0 comments on commit 885c007

Please sign in to comment.