File tree Expand file tree Collapse file tree 1 file changed +37
-16
lines changed
docs/Leetcode_Solutions/Python Expand file tree Collapse file tree 1 file changed +37
-16
lines changed Original file line number Diff line number Diff line change 1- ### 231. Power of Two
1+ # 231. Power of Two
22
3+ ** <font color =red >难度: Easy</font >**
34
5+ ## 刷题内容
46
5- 题目:
7+ > 原题连接
68
7- < https://leetcode.com/problems/power-of-two/ >
9+ * https://leetcode.com/problems/power-of-two/description/
810
9- 难度:
11+ > 内容描述
1012
11- Easy
13+ ```
14+ Given an integer, write a function to determine if it is a power of two.
15+
16+ Example 1:
17+
18+ Input: 1
19+ Output: true
20+ Explanation: 20 = 1
21+ Example 2:
22+
23+ Input: 16
24+ Output: true
25+ Explanation: 24 = 16
26+ Example 3:
1227
28+ Input: 218
29+ Output: false
30+ ```
1331
32+ ## 解题方案
1433
15- 思路:
34+ > 思路 1
35+ ****** - 时间复杂度: O(1)****** - 空间复杂度: O(1)******
1636
1737
1838
19- power of two 那是这个数字的binary 表示一定只有一个1
39+ power of two 那是这个数字的 binary 表示一定只有一个1
2040
21- 套用以前的代码[ leetcode191] ( https://github.com/Lisanaaa/thinking_in_lc /blob/master/191._number_of_1_bits.md )
41+ 套用以前的代码[ leetcode191] ( https://github.com/apachecn/awesome-algorithm /blob/master/docs/Leetcode_Solutions/Python /191._number_of_1_bits.md )
2242
2343这样会超时
2444
2545```
2646class Solution(object):
27- def isPowerOfTwo(self, n): # 此法超时
28- """
47+ def isPowerOfTwo(self, n): # 此法超时
48+ """
2949 :type n: int
3050 :rtype: bool
3151 """
3252 cnt = 0
3353 while n != 0:
34- n &= n - 1
35- cnt += 1
54+ n &= n - 1
55+ cnt += 1
3656 return cnt == 1
3757```
3858
39-
59+ > 思路 2
60+ ****** - 时间复杂度: O(1)****** - 空间复杂度: O(1)******
4061
4162跟power of three一样递归,可以AC
4263
@@ -55,14 +76,14 @@ class Solution(object):
5576 return True
5677 if n % 2 == 0 :
5778 return self .isPowerOfTwo(n/ 2 )
58- return False
59-
79+ return False
6080```
6181
6282
6383
6484
65-
85+ > 思路 3
86+ ****** - 时间复杂度: O(1)****** - 空间复杂度: O(1)******
6687
6788
6889也是有[ 算法的wikipedia page] ( https://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two )
You can’t perform that action at this time.
0 commit comments