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

1 Answer

0 votes
import java.math.BigInteger

/**
 * Returns the N-th digit of a BigInteger counting from the right.
 *
 * Examples:
 * getNthDigitFromRightBigInteger(BigInteger("12345"), 1) == 5
 * getNthDigitFromRightBigInteger(BigInteger("12345"), 2) == 4
 * getNthDigitFromRightBigInteger(BigInteger("12345"), 3) == 3
 */
fun getNthDigitFromRightBigInteger(inputNumber: BigInteger, digitPosition: Int): Int {

    require(digitPosition > 0) {
        "Digit position must be greater than 0."
    }

    val absoluteNumber = inputNumber.abs()

    val divisor = BigInteger.TEN.pow(digitPosition - 1)

    return absoluteNumber
        .divide(divisor)
        .mod(BigInteger.TEN)
        .toInt()
}

fun main() {
    val largeNumber = BigInteger("123456789712345678908234567890")

    println(getNthDigitFromRightBigInteger(largeNumber, 10))
}


/*
Output:

8

*/

 



answered 19 hours ago by avibootz
...