File tree 1 file changed +70
-0
lines changed
1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change
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).
You can’t perform that action at this time.
0 commit comments