We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent f444988 commit fff4f01Copy full SHA for fff4f01
counting-bits/sonjh1217.swift
@@ -0,0 +1,35 @@
1
+class Solution {
2
+ // Brute Force
3
+ // O(nlogn) time / O(n) space
4
+ func countBits(_ n: Int) -> [Int] {
5
+ var numberOfOnes = [Int]()
6
+ for i in 0...n {
7
+ var numberOfOne = 0
8
+ var i = i
9
+
10
+ while i > 0 {
11
+ numberOfOne += i & 1
12
+ i >>= 1
13
+ }
14
15
+ numberOfOnes.append(numberOfOne)
16
17
18
+ return numberOfOnes
19
20
21
+ // Dynamic Programming
22
+ // O(n) time / O(n) space
23
+ func countBitsDP(_ n: Int) -> [Int] {
24
+ var numberOfOnes = [Int](repeating: 0, count: n + 1)
25
+ if n < 1 {
26
27
28
29
+ for i in 1...n {
30
+ numberOfOnes[i] = numberOfOnes[i >> 1] + (i & 1)
31
32
33
34
35
+}
0 commit comments