Skip to content

Commit ac55f6d

Browse files
committed
Add solution 231
1 parent 453aaf6 commit ac55f6d

File tree

3 files changed

+63
-2
lines changed

3 files changed

+63
-2
lines changed

README.md

+1-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@
88

99
</center>
1010

11-
# <center>LeetCode Solutions</center>
12-
1311
## Introduction
1412
Complete solutions to Leetcode problems, updated daily.
1513

@@ -29,6 +27,7 @@ Complete solutions to Leetcode problems, updated daily.
2927
| 189 | [Rotate Array](https://github.com/yanglbme/leetcode/tree/master/solution/189.Rotate%20Array) | `Array` |
3028
| 198 | [House Robber](https://github.com/yanglbme/leetcode/tree/master/solution/198.House%20Robber) | `Dynamic Programming` |
3129
| 203 | [Remove Linked List Elements](https://github.com/yanglbme/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements) | `Linked List` |
30+
| 231 | [Power of Two](https://github.com/yanglbme/leetcode/tree/master/solution/231.Power%20of%20Two) | `Math`, `Bit Manipulation` |
3231
| 237 | [Delete Node in a Linked List](https://github.com/yanglbme/leetcode/tree/master/solution/237.Delete%20Node%20in%20a%20Linked%20List) | `Linked List` |
3332
| 344 | [Reverse String](https://github.com/yanglbme/leetcode/tree/master/solution/344.Reverse%20String) | `Two Pointers`, `String` |
3433
| 876 | [Middle of the Linked List](https://github.com/yanglbme/leetcode/tree/master/solution/876.Middle%20of%20the%20Linked%20List) | `Linked List` |

solution/231.Power of Two/README.md

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
## 2的幂
2+
### 题目描述
3+
4+
给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
5+
6+
示例 1:
7+
```
8+
输入: 1
9+
输出: true
10+
解释: 2^0 = 1
11+
```
12+
13+
示例 2:
14+
```
15+
输入: 16
16+
输出: true
17+
解释: 2^4 = 16
18+
```
19+
20+
示例 3:
21+
```
22+
输入: 218
23+
输出: false
24+
```
25+
26+
### 解法
27+
可以利用 2^31 对该数取余,结果为 0 则为 2 的幂次方。
28+
```java
29+
class Solution {
30+
public boolean isPowerOfTwo(int n) {
31+
return n > 0 && 1073741824 % n == 0;
32+
}
33+
}
34+
```
35+
36+
也可以循环取余,每次除以 2,判断最终结果是否为 1。
37+
```java
38+
class Solution {
39+
public boolean isPowerOfTwo(int n) {
40+
if (n < 1) {
41+
return false;
42+
}
43+
44+
while (n % 2 == 0) {
45+
n >>= 1;
46+
}
47+
return n == 1;
48+
}
49+
}
50+
```
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution {
2+
public boolean isPowerOfTwo(int n) {
3+
if (n < 1) {
4+
return false;
5+
}
6+
7+
while (n % 2 == 0) {
8+
n >>= 1;
9+
}
10+
return n == 1;
11+
}
12+
}

0 commit comments

Comments
 (0)