Skip to content

Commit 89cfe9b

Browse files
committed
Extract Long.digitCount() - a function that counts digits of a Long number
1 parent ff25fb1 commit 89cfe9b

File tree

3 files changed

+33
-12
lines changed

3 files changed

+33
-12
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package de.ronny_h.aoc.extensions
2+
3+
/**
4+
* Counts the number of digits of the given Long number.
5+
*/
6+
fun Long.digitCount(): Int {
7+
if (this == 0L) return 1
8+
9+
var count = 0
10+
var currentNumber = this
11+
while (currentNumber > 0) {
12+
currentNumber /= 10
13+
count++
14+
}
15+
return count
16+
}

src/main/kotlin/de/ronny_h/aoc/year24/day11/PlutonianPebbles.kt

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package de.ronny_h.aoc.year24.day11
22

33
import de.ronny_h.aoc.AdventOfCode
4+
import de.ronny_h.aoc.extensions.digitCount
45
import de.ronny_h.aoc.extensions.memoize
56

67
fun main() = PlutonianPebbles().run(193899, 229682160383225)
@@ -12,18 +13,6 @@ class PlutonianPebbles : AdventOfCode<Long>(2024, 11) {
1213
.map(String::toLong)
1314
.toMutableList()
1415

15-
private fun Long.digitCount(): Int {
16-
if (this == 0L) return 1
17-
18-
var count = 0
19-
var currentNumber = this
20-
while (currentNumber > 0) {
21-
currentNumber /= 10
22-
count++
23-
}
24-
return count
25-
}
26-
2716
private fun tenToPowerOf(digitCount: Int): Int {
2817
var tens = 10
2918
repeat((digitCount / 2) - 1) {
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package de.ronny_h.aoc.extensions
2+
3+
import io.kotest.core.spec.style.StringSpec
4+
import io.kotest.data.forAll
5+
import io.kotest.data.row
6+
import io.kotest.matchers.shouldBe
7+
8+
class DigitsTest : StringSpec({
9+
"Digits are counted" {
10+
forAll(
11+
row(0L, 1), row(123L, 3), row(1234567890, 10)
12+
) { number, digits ->
13+
number.digitCount() shouldBe digits
14+
}
15+
}
16+
})

0 commit comments

Comments
 (0)