File tree Expand file tree Collapse file tree 1 file changed +37
-14
lines changed
problems/342. Power of Four Expand file tree Collapse file tree 1 file changed +37
-14
lines changed Original file line number Diff line number Diff line change 1
1
# 342. Power of Four
2
2
3
- ## Description
3
+ ## # 1 暴力搜索 [ TLE ]
4
4
5
- ```
6
- Difficulty: Easy
7
- Total Accepted:67.4K
8
- Total Submissions:175.3K
9
- Contributor: LeetCode
5
+ ### 思路
6
+
7
+ 依次搜索出所有的4的幂,如果与发现其中存在与输入值一样的,就返回true,否则就返回false。
8
+
9
+ ### 算法
10
+
11
+ ``` java
12
+ class Solution {
13
+ public boolean isPowerOfFour (int num ) {
14
+ if (num == 1 )
15
+ return true ;
16
+ if (num < 4 )
17
+ return false ;
18
+ int mul = 1 ;
19
+ while (mul < num){
20
+ mul *= 4 ;
21
+ if (mul == num)
22
+ return true ;
23
+ }
24
+ return false ;
25
+ }
26
+ }
10
27
```
11
28
12
- Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
29
+ ### 复杂度分析:
13
30
14
- ** Example: **
15
- Given num = 16, return true. Given num = 5, return false.
31
+ - 时间复杂度:$O(log_4num)$
32
+ - 空间复杂度:$O(1)$
16
33
17
- ***
34
+ ## #2 位操作[ AC]
35
+ ### 思路
18
36
19
- ## Solution
20
- 关于这道题目,前面有做过判断一个数是否为2的幂的问题,当时做的时候是把数值用二进制的域来看待,这样就可以发现,2的幂在2进制下的规律是,最高位为1,其他位为0,这道题要求4的幂。首先,4的幂是2的幂的一个子集,我们可以在上道题的基础上,去思考这道题。复杂问题简单化思想,把该问题,转化为在求2的幂的解空间里求特定的一部分解空间。第一步,先求出2的幂。第二步,在求出的结果上,与上我们进一步的限制条件。关于这类题的限制条件,就是用二进制与的特殊性,也就是1去与任何数位可以筛选该数位的功能去给出我们的限制条件。
37
+ 关于这道题目,前面有做过判断一个数是否为2的幂的问题,当时做的时候是把数值用二进制的域来看待,这样就可以发现,2的幂在2进制下的规律是,最高位为1,其他位为0,这道题要求4的幂。首先,4的幂是2的幂的一个子集,我们可以在之前题目的基础上,去思考这道题。复杂问题简单化思想,把该问题,转化为在求2的幂的解空间里求特定的子空间。第一步,先求出2的幂。第二步,在所有2的幂里面,找到4的幂。
38
+
39
+ 对于第一步,我们通过` x&(x-1)==0 ` 来过滤出2的幂,对于第二步呢?我们怎么判断,其实4的幂比2的幂多了一个限制条件,就是,它的1在奇数位上。所以,我们进一步用` 0x55555555 ` 过滤出4的幂。
40
+
41
+ ### 算法
21
42
22
43
``` java
23
44
public class Solution {
@@ -29,6 +50,8 @@ public class Solution {
29
50
}
30
51
```
31
52
32
- ***
53
+ ### 复杂度分析
54
+
55
+ - 时间复杂度:$O(1)$
56
+ - 空间复杂度:$O(1)$
33
57
34
- ** enjoy life, coding now! : D **
You can’t perform that action at this time.
0 commit comments