forked from SuperJolly/awesome-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 201._Bitwise_AND_of_Numbers_Range.md
- Loading branch information
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
67 changes: 67 additions & 0 deletions
67
docs/Leetcode_Solutions/201._Bitwise_AND_of_Numbers_Range.md
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
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 | ||
``` |