How to get the Nth digit of a number from the right in Kotlin

1 Answer

0 votes
/**
 * Returns the N-th digit of a number counting from the right.
 *
 * Examples:
 * getNthDigitFromRight(12345, 1) == 5
 * getNthDigitFromRight(12345, 2) == 4
 * getNthDigitFromRight(12345, 3) == 3
 *
 * @param inputNumber The number to inspect.
 * @param digitPosition The digit position (1-based, from the right).
 * @return The digit at the specified position.
 * @throws IllegalArgumentException If digitPosition is less than 1.
 */
fun getNthDigitFromRight(inputNumber: Long, digitPosition: Int): Int {
    require(digitPosition > 0) {
        "Digit position must be greater than 0."
    }

    // Handle negative numbers.
    val absoluteNumber = kotlin.math.abs(inputNumber)

    // Calculate 10^(digitPosition - 1) using integer arithmetic.
    var divisor = 1L

    for (positionIndex in 1 until digitPosition) {
        divisor *= 10
    }

    // Shift the desired digit to the ones place.
    val shiftedNumber = absoluteNumber / divisor

    // Extract the digit.
    return (shiftedNumber % 10).toInt()
}

fun main() {
    val inputNumber = 12745L

    val firstDigitFromRight =
        getNthDigitFromRight(inputNumber, 1)

    val thirdDigitFromRight =
        getNthDigitFromRight(inputNumber, 3)

    val fifthDigitFromRight =
        getNthDigitFromRight(inputNumber, 5)

    println("Number: $inputNumber")
    println("1st digit from right: $firstDigitFromRight")
    println("3rd digit from right: $thirdDigitFromRight")
    println("5th digit from right: $fifthDigitFromRight")
}


/*
run:

Number: 12745
1st digit from right: 5
3rd digit from right: 7
5th digit from right: 1

*/

 



answered Oct 14 by avibootz
...