Skip to content

Commit b59836c

Browse files
add kotlin solution for 338 Counting-Bits.kt
1 parent c7bc6e7 commit b59836c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)