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 would 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, one, one, ... is a 0, which are part of the number 10.
Here are the practices of C + +
We first analyze the relationship between the natural number sequence and the number of digits, the first nine numbers are 1 digits, then 10 to 99 of the total 90 digits are two digits, 100 to 999 of these 900 are three, then this is very regular, we can define a variable cnt, initialized to 9, and then each cycle to expand 10 times times, Then use a variable len to record the number of digits in the current loop interval, in addition, a variable start is used to record the first number in the current cyclic interval, and we subtract len*cnt (the total number of intervals) per loop, and when N falls into a certain interval, then (n-1)/ Len is the coordinates of the target number in that range, plus start is to get the target number, and then we will be the target number start into a string, (n-1)%len is the required target bit, and finally do not forget to consider an int overflow problem, we simply apply all the variables to the long integer good,
The code is as follows:
#include <iostream> #include <vector> #include <map> #include < unordered_map> #include <set> #include <unordered_set> #include <queue> #include <stack> # Include <string> #include <climits> #include <algorithm> #include <sstream> #include < functional> #include <bitset> #include <numeric> #include <cmath> #include <regex> using name
Space Std;
Class Solution {public:int findnthdigit (int n) {long Long Lenofdit = 1, start = 1, count = 9;
while (n > Lenofdit*count) {n-= Lenofdit*count;
Lenofdit + 1;
Count *= 10;
Start *= 10;
int num = start + (n-1)/lenofdit;
string s = to_string (num);
Return s[(n-1)% lenofdit]-' 0 '; }
};