Kotlin Program to find the second largest digit of a number


In this program, You will learn how to find the second largest digit of a number in Kotlin.


1234 => 3

2312 => 2

Example: How to find the second largest digit of a number in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    var n: Int
    var r: Int
    var rev = 0
    var lar = 0
    var sl = 0

    var sc = Scanner(System.`in`)

    print("Enter a number:")
    n = sc.nextInt()

    while (n > 0) {
        r = n % 10
        if (lar < r) {
            lar = r
        }
        rev = rev * 10 + r
        n /= 10
    }

    n = rev;
    while (n > 0) {
        r = n % 10
        if (lar != r) {
            if (sl < r) {
                sl = r
            }
        }
        n /= 10
    }

    println("Second largest digit:$sl")
}

Output:

Enter a number:3453
Second largest digit:4