Write a Kotlin Program to Count Number of Digits in an Integer

In Kotlin, it is straightforward to count the number of digits in an integer.

Here’s a simple program that demonstrates how to do it.

fun countDigits(number: Int): Int {
var count = 0
var num = number
while (num != 0) {
num /= 10
++count
}
return count
}

fun main() {
val number = 123456789
val digitCount = countDigits(number)
println("Number of digits in $number is $digitCount")
}

In this program, we define a function called countDigits that takes an integer as a parameter and returns the number of digits in it.

We first initialize a count variable to 0 and a temporary variable called num to the value of the input parameter.

We then use a while loop to repeatedly divide num by 10 and increment the count variable until num becomes 0.

The number of times we divide by 10 is the number of digits in the original number.

In the main function, we declare a variable called number and assign it a value of 123456789.

We then call the countDigits function with this value and store the result in a variable called digitCount.

Finally, we print the result using a formatted string.

That’s it! This program is short and straightforward, but it should give you a good understanding of how to count the number of digits in an integer in Kotlin.