File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
May-LeetCoding-Challenge/28-Counting-Bits Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ class CountingBitsKotlin338 {
2
+ /*
3
+ 0 -> 0
4
+ 1 -> 1
5
+
6
+ 2 -> 1
7
+ 3 -> 2
8
+
9
+ 4 -> 1
10
+ 5 -> 2
11
+ 6 -> 2
12
+ 7 -> 3
13
+ */
14
+ fun countBits (num : Int ): IntArray {
15
+ val result = IntArray (num + 1 )
16
+ for (index in result.indices) {
17
+ result[index] = result[index.shr(1 )] + if (index % 2 == 0 ) 0 else 1
18
+ }
19
+ return result
20
+ }
21
+
22
+ /*
23
+ fun countBits(num: Int): IntArray {
24
+ return IntRange(0, num).map(this::bitCountOne).toIntArray()
25
+ }
26
+
27
+ private fun bitCountOne(target: Int): Int {
28
+ var count = 0
29
+ var n = target
30
+ while (n != 0) {
31
+ count += n % 2
32
+ n /= 2
33
+ }
34
+ return count
35
+ }
36
+ */
37
+ }
38
+
39
+ fun main () {
40
+ val solution = CountingBitsKotlin338 ()
41
+ // 0 1 1 2 1 2
42
+ solution.countBits(5 ).forEach(::print)
43
+ }
You can’t perform that action at this time.
0 commit comments