[LeetCode] Nth Digit

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).

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int findNthDigit(int n) {
long len = 1, start = 1;
for(; n > ((start<<3) + start) * len; start = (start<<3) + (start<<1), len++) {
n -= (((start<<3) + start) * len);
}
n--;
return to_string(start + n / len)[n % len] & 0b1111;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/13/PS/LeetCode/nth-digit/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.