Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of digits in Kotlin

Tags:

kotlin

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.

like image 766
arslancharyev31 Avatar asked Mar 22 '17 11:03

arslancharyev31


2 Answers

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)
like image 122
marstran Avatar answered Oct 04 '22 11:10

marstran


This task could be solved recursively as following:

  • check it the number fits in the range -9..9. If that's true, the result is 1.
  • otherwise divide the number by 10, count digits in the result, and add 1 to that count.
fun numberOfDigits(n: Int): Int = 
    when (n) {
        in -9..9 -> 1
        else -> 1 + numberOfDigits(n / 10)
    } 
like image 31
Ilya Avatar answered Oct 04 '22 11:10

Ilya