I'm currently counting number of digits using simple string.length approach:
val number = 829
val length = number.toString().length
I wonder whether this is a good way or there is a more appropriate way to do that in Kotlin.
You can use the standard Java-math library in java.lang.Math
(edit: since Kotlin 1.2, use kotlin.math
). The log10
function will give you the length of the number minus 1 (with some exceptions). This function works with doubles though, so you have to convert back and forth.
A length
function could be written like this in Kotlin:
fun Int.length() = when(this) {
0 -> 1
else -> log10(abs(toDouble())).toInt() + 1
}
Then you can call it like this:
println(829.length()) // Prints 3
println((-1234).length()) // Prints 4 (it disregards the minus sign)
This task could be solved recursively as following:
-9..9
. If that's true, the result is 1.fun numberOfDigits(n: Int): Int =
when (n) {
in -9..9 -> 1
else -> 1 + numberOfDigits(n / 10)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With