Nth Digit LeetCode

 Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].


 


Example 1:


Input: n = 3

Output: 3

Example 2:


Input: n = 11

Output: 0

Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.


class Solution {
    public int findNthDigit(int n) {
        int digitLength = 1; // Numbers start as 1-digit
        long count = 9;      // 9 one-digit numbers
        long start = 1;      // Starting number in this range

        // Step 1: Find which digit-length group contains the nth digit
        while (n > digitLength * count) {
            n -= digitLength * count; // Remove the full range of digits
            digitLength++;            // Move to 2-digit numbers
            count *= 10;              // 90 two-digit numbers
            start *= 10;              // Starting number like 10, 100, etc.
        }

        // Step 2: Find the number that holds the nth digit
        long number = start + (n - 1) / digitLength;

        // Step 3: Find the digit in the number
        String numStr = String.valueOf(number);
        int index = (n - 1) % digitLength;

        return numStr.charAt(index) - '0';
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence