How to find the digit next to a given digit in a number with Kotlin

1 Answer

0 votes
fun findNextDigit(number: Int, target: Int): Int {
    var num = number
    var next = -1

    while (num > 0) {
        val current = num % 10
        num /= 10

        if (current == target) {
            return next
        }

        next = current
    }

    return -1
}

fun main() {
    val number = 8902741
    val target = 2

    val result = findNextDigit(number, target)

    if (result != -1) {
        println("The digit after $target in $number is $result.")
    } else {
        println("The digit $target is not found or has no next digit in $number.")
    }
}



/*
run:

The digit after 2 in 8902741 is 7.

*/

 



answered Oct 19 by avibootz
...