LeetCode in Kotlin

4022. K-th Digit in Infinite String

Medium

You are given an integer k.

An infinite string is formed by concatenating the decimal representations of the positive integers, without separators.

For every nonnegative integer b, block b contains the positive integers from 10 * b through 10 * b + 9. The integers in each block are appended as follows:

Therefore, the string starts with the integers 1 through 9, followed by 19 through 10, then 20 through 29, then 39 through 30, and so on.

Return the kth digit (1-indexed) of this string.

Example 1:

Input: k = 4

Output: 4

Explanation:

The string begins as "123456789..". The 4th digit is '4'.

Example 2:

Input: k = 15

Output: 7

Explanation:

The string begins as "123456789191817..". The 15th digit is '7'.

Example 3:

Input: k = 11

Output: 9

Explanation:

The string begins as "12345678919..". The 11th digit is '9'.

Constraints:

Solution

class Solution {
    fun kthDigit(k: Long): Int {
        if (k <= 9) {
            return k.toInt()
        }
        var remaining = k - 9
        var power10: Long = 10
        var d = 2
        while (true) {
            val firstBlock = power10 / 10
            val lastBlock = power10 - 1
            val numberOfBlocks = lastBlock - firstBlock + 1
            val digitsPerBlock = 10L * d
            val groupDigits = numberOfBlocks * digitsPerBlock
            if (remaining > groupDigits) {
                remaining -= groupDigits
                power10 *= 10
                d++
                continue
            }
            val zeroBased = remaining - 1
            val blockOffset = zeroBased / digitsPerBlock
            val positionInBlock = zeroBased % digitsPerBlock
            val b = firstBlock + blockOffset
            val numberIndex = positionInBlock / d
            val digitIndex = (positionInBlock % d).toInt()
            val number: Long
            if (b % 2 == 0L) {
                number = 10 * b + numberIndex
            } else {
                number = 10 * b + 9 - numberIndex
            }
            var divisor: Long = 1
            for (i in 0..<d - 1 - digitIndex) {
                divisor *= 10
            }
            return ((number / divisor) % 10).toInt()
        }
    }
}