Skip to content

Commit f575525

Browse files
committed
Power of Two.
1 parent c38b6b1 commit f575525

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
Given an integer n, return true if it is a power of two. Otherwise, return false.
3+
4+
An integer n is a power of two, if there exists an integer x such that n == 2x.
5+
6+
 
7+
8+
Example 1:
9+
Input: n = 1
10+
Output: true
11+
Explanation: 20 = 1
12+
13+
Example 2:
14+
Input: n = 16
15+
Output: true
16+
Explanation: 24 = 16
17+
18+
Example 3:
19+
Input: n = 3
20+
Output: false
21+
 
22+
23+
Constraints:
24+
- -231 <= n <= 231 - 1
25+
 
26+
27+
Follow up: Could you solve it without loops/recursion?
28+
*/
29+
class Solution {
30+
func isPowerOfTwo(_ n: Int) -> Bool {
31+
if n <= 0 { return false }
32+
var x = 0
33+
while pow(2, pow: x) <= n {
34+
x += 1
35+
}
36+
return pow(2, pow: x - 1) == n
37+
}
38+
39+
private func pow(_ base: Int, pow: Int) -> Int {
40+
var res = 1
41+
for _ in 0..<pow {
42+
res *= base
43+
}
44+
return res
45+
}
46+
}
47+
48+
let s = Solution()
49+
let r = s.isPowerOfTwo(0)
50+
print(r)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/231.Power of Two.playground/playground.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,4 @@
5151
49. [Implement Stack using Queues](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/225.Implement%20Stack%20using%20Queues.playground/Contents.swift)
5252
50. [Invert Binary Tree](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/226.Invert%20Binary%20Tree.playground/Contents.swift)
5353
51. [Summary Ranges](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/228.Summary%20Ranges.playground/Contents.swift)
54+
52. [Power of Two](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/231.Power%20of%20Two.playground/Contents.swift)

0 commit comments

Comments
 (0)