DEV Community

Discussion on: Daily Challenge #264 - Digital Root

Collapse
 
johnmilimo profile image
JMW

n % 9 is such an interesting property! But since I had no knowledge of it, I went with a naive solution in KOTLIN which I cracked within a few minutes:

fun digitalRoot(number: Int): Int {
    return if(number < 10) {
        number
    } else {
        val digits = number.toString().split("")
        var sum = 0
        digits.forEach {
            val digit = it.toIntOrNull()
            if(digit != null) { sum += digit}
        }
        digitalRoot(sum)
    }
}