Thinking process

find the length of the number where the nth digit is from

  • iterate over ranges
  • subtract the number of digits in each range

find the actual number where the nth digit is from

  • number of numbers after start

find the nth digit and return

  • charAt

API Method

Character
  • convert to int => Character.getNumericValue(c)
public class Solution {
    public int findNthDigit(int n) {
        int start = 1;
        int len = 1;

        while(n > 9 * Math.pow(10, len - 1) * len) {
            start *= 10;
            n = n - 9 * (int)Math.pow(10, len - 1) * len;
            len++;
        }

        int num = start + (n - 1) / len;
        String str = String.valueOf(num);

        return Character.getNumericValue(str.charAt((n - 1) % len));
    }
}

results matching ""

    No results matching ""