Kotlin Program to Count Number of Digits in an Integer

Example 1: Count Number of Digits in an Integer

fun main(args: Array<String>) {
    var count = 0
    var num = 1234567

    while (num != 0) {
        num /= 10
        ++count
    }

    println("Number of digits: $count")
}

When you run the program, the output will be:

Number of digits: 7

In this program, while loop is iterated until the test expression num != 0 is evaluated to 0 (false).

  • After first iteration, num will be divided by 10 and its value will be 345. Then, the count is incremented to 1.
  • After second iteration, the value of num will be 34 and the count is incremented to 2.
  • After third iteration, the value of num will be 3 and the count is incremented to 3.
  • After fourth iteration, the value of num will be 0 and the count is incremented to 4.
  • Then the test expression is evaluated to false and the loop terminates.

Here's the equivalent Java code: Java Program to Count Number of Digits in an Integer

Did you find this article helpful?