Skip to content

Commit f6a75fa

Browse files
committed
feat: solve No.231
1 parent ef5667c commit f6a75fa

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

201-300/231. Power of Two.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# 231. Power of Two
2+
3+
- Difficulty: Easy.
4+
- Related Topics: Math, Bit Manipulation, Recursion.
5+
- Similar Questions: Number of 1 Bits, Power of Three, Power of Four.
6+
7+
## Problem
8+
9+
Given an integer `n`, return **`true` if it is a power of two. Otherwise, return `false`**.
10+
11+
An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`.
12+
13+
 
14+
Example 1:
15+
16+
```
17+
Input: n = 1
18+
Output: true
19+
Explanation: 20 = 1
20+
```
21+
22+
Example 2:
23+
24+
```
25+
Input: n = 16
26+
Output: true
27+
Explanation: 24 = 16
28+
```
29+
30+
Example 3:
31+
32+
```
33+
Input: n = 3
34+
Output: false
35+
```
36+
37+
 
38+
**Constraints:**
39+
40+
41+
42+
- `-231 <= n <= 231 - 1`
43+
44+
45+
 
46+
**Follow up:** Could you solve it without loops/recursion?
47+
48+
## Solution
49+
50+
```javascript
51+
/**
52+
* @param {number} n
53+
* @return {boolean}
54+
*/
55+
var isPowerOfTwo = function(n) {
56+
if (n <= 0) return false;
57+
if (n === 1) return true;
58+
if (n % 2) return false;
59+
return isPowerOfTwo(n / 2);
60+
};
61+
```
62+
63+
**Explain:**
64+
65+
nope.
66+
67+
**Complexity:**
68+
69+
* Time complexity : O(log(n)).
70+
* Space complexity : O(1).

0 commit comments

Comments
 (0)