toDigits() function for Int

Hello everyone,

I’m really missing a useful function in Kotlin. Right now the only way to convert an Int to a List of Digits (Int) is to create a method or use toString which is rather ugly.
Could you provide a function for the Int class which converts a number to its digits via modulo 10 and dividing by 10?

Thanks

2 Likes

I don’t really think it’s necessary. This is so rarely used I can’t think of any real usage of this so it is overkill for standard library.

1 Like

fun Int.toDigits(): List<Int> = toString().map { it.toString().toInt() }

Unfortunately this is as close as you can really get. That’s why you write your own extension methods for it. You only have to write the ugly once and you can write it your nice way every other time! The joy of programming.

1 Like

It can be non-optimal (if JVM doesn’t have exact this optimization).

Why is it ugly?

I guess the fact that you need to call toString().toInt() instead of calling toInt() directly is a bit annoying, but you only have to write this once so I don’t care.

Coroutine version:

fun Int.toDigits(base: Int = 10): List<Int> = sequence {
    var n = this@toDigits
    require(n >= 0)
    while (n != 0) {
        yield(n % base)
        n /= base
    }
}.toList()

Items are ordered as unit, tens and so on.
You can use asReversed() to get the Arab convention.

5 Likes