Find the nth
digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
求连续自然数中的第n位数字
- n is positive and will fit within the range of a 32-bit signed integer (n < 2^31).
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.
// 区间 区间中每个数字所占位数 区间内数字所占的所有位数
// 1-9 1 9位
//10-99 2 (99-9)*2=9*10^(2-1)*2
//100-999 3 9*10^(3-1)*3
思路 1.先找出在哪个区间
2.找出在这个区间的哪个数中
3.找出在这个数的哪一位
int NthDigit(int n)
{
int digit = 1; //n所在范围所有数字都占了digit位数字
long total = 0; //到n所在范围总共有多少位数字
while (true)
{
long top = total + 9 * digit * (long)Mathf.Pow(10, digit - 1);
if (n >= total && n <= top)
break;
digit++;
total = top;
}
total += 1;
long dealt = n - total; //比上一个范围多了多少个数字
int num = (int)Mathf.Pow(10, digit - 1) + (int)dealt / digit; //找出在这个范围的具体哪一个数字
int remain = (int)dealt % digit; //找出在这个数字的具体哪一位
return num.ToString()[remain] - '0';
}