1.2 Nth Digit

Description

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note: n is positive and will fit within the range of a 32-bit signed integer (n < 231).

Example 1:

Input: 3

Output: 3 Example 2:

Input: 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.

Method

we need to find the nth digits firstly, we need to find the number of that digits and then find the nth digits on this number

Time and Space Complexity

O(n)

Code

public class Solution { public int findNthDigit(int n) { n -= 1; int first = 1; int digits = 1; while (n / 9 / first / digits >= 1){ n -= 9 first digits; digits++; first *= 10; } return (first + n / digits + "").charAt(n % digits) - '0'; } }

results matching ""

    No results matching ""