Skip to content

Commit 183f9b1

Browse files
committed
feat: Add solution for LeetCode problem 338
1 parent 5063d27 commit 183f9b1

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

counting-bits/WhiteHyun.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//
2+
// 338. Counting Bits
3+
// https://leetcode.com/problems/counting-bits/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/05/19.
7+
//
8+
9+
final class Solution {
10+
11+
// MARK: - Time Complexity: O(n), Space Complexity: O(n)
12+
13+
func countBits(_ n: Int) -> [Int] {
14+
var array: [Int] = .init(repeating: 0, count: n + 1)
15+
for i in stride(from: 1, through: n, by: 1) {
16+
array[i] = array[i >> 1] + (i & 1)
17+
}
18+
return array
19+
}
20+
21+
// MARK: - nonzeroBitCount
22+
23+
func countBits2(_ n: Int) -> [Int] {
24+
return (0...n).map(\.nonzeroBitCount)
25+
}
26+
27+
}

0 commit comments

Comments
 (0)