Algorithm
Problem Name: 400. Nth Digit
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.
Constraints:
1 <= n <= 231 - 1
Code Examples
#1 Code Example with C Programming
Code -
C Programming
int findNthDigit(int n) {
unsigned int i, j, k;
i = j = 1;
while (n > 9 * i * j) {
n -= 9 * i * j;
j *= 10;
i ++;
}
k = j + (n - 1) / i;
for (j = (n - 1) % i; j < i - 1; j ++) {
k = k / 10;
}
return k % 10;
}
Copy The Code &
Try With Live Editor
Input
n = 3
Output
3
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const findNthDigit = function(n) {
let start = 1
let len = 1
let base = 9
while(n > len * base) {
n = n - len * base
len++
start *= 10
base *= 10
}
let target = start + (n - 1) / len
let reminder = (n - 1) % len
return (''+target).charAt(reminder)
};
Copy The Code &
Try With Live Editor
Input
n = 3
Output
3