Skip to main content
Back to problems
#400
Medium Algorithms

Nth digit

Math Binary Search
37.4% acceptance
Jan 12, 2026
1241
2136
Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn find_nth_digit(n: i32) -> i32 {
    let mut n = n as i64;
    let mut digits = 1i64;
    let mut count = 9i64;
    let mut start = 1i64;
    
    while n > digits * count {
      n -= digits * count;
      digits += 1;
      count *= 10;
      start *= 10;
    }
    
    let num = start + (n - 1) / digits;
    let digit_index = ((n - 1) % digits) as usize;
    
    num.to_string().chars().nth(digit_index).unwrap().to_digit(10).unwrap() as i32
  }
}