LeetCode-in-Java

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

public class Solution {
    public int kthDigit(long k) {
        if (k <= 9) {
            return (int) k;
        }
        long remaining = k - 9;
        long power10 = 10;
        int d = 2;
        while (true) {
            long firstBlock = power10 / 10;
            long lastBlock = power10 - 1;
            long numberOfBlocks = lastBlock - firstBlock + 1;
            long digitsPerBlock = 10L * d;
            long groupDigits = numberOfBlocks * digitsPerBlock;
            if (remaining > groupDigits) {
                remaining -= groupDigits;
                power10 *= 10;
                d++;
                continue;
            }
            long zeroBased = remaining - 1;
            long blockOffset = zeroBased / digitsPerBlock;
            long positionInBlock = zeroBased % digitsPerBlock;
            long b = firstBlock + blockOffset;
            long numberIndex = positionInBlock / d;
            int digitIndex = (int) (positionInBlock % d);
            long number;
            if (b % 2 == 0) {
                number = 10 * b + numberIndex;
            } else {
                number = 10 * b + 9 - numberIndex;
            }
            long divisor = 1;
            for (int i = 0; i < d - 1 - digitIndex; i++) {
                divisor *= 10;
            }
            return (int) ((number / divisor) % 10);
        }
    }
}