400. Nth Digit

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.

Rust Solution

struct Solution;

impl Solution {
    fn find_nth_digit(n: i32) -> i32 {
        let mut size = 1;
        let mut start = 1;
        let mut count = 9;
        let mut n = n as usize;
        while n > size * count {
            n -= size * count;
            size += 1;
            start *= 10;
            count *= 10;
        }
        let x = start + (n - 1) / size;
        let v: Vec<i32> = format!("{}", x)
            .bytes()
            .map(|b| (b - b'0') as i32)
            .collect();
        v[(n - 1) % size]
    }
}
#[test]
fn test() {
    let n = 3;
    let res = 3;
    assert_eq!(Solution::find_nth_digit(n), res);
    let n = 11;
    let res = 0;
    assert_eq!(Solution::find_nth_digit(n), res);
}

Having problems with this solution? Click here to submit an issue on github.