数学:
- 输入查找第n个位(1 ≤ n ≤ 2147483647),至少要有31268个组,才能使得数字序列达到有第2147483647位。
- 2147483647刚好是int的正整数最大极限值( ): 用int定义n。但是s[31268]存在超过2147483647的位数,因此要用unsigned 或long 去定义s[].
- 两个数学难点: (int)log10((double)i)+1, (i-1)/(int)pow((double)10,len-pos)%10。
- log()和pow()函数:传参的类型需要为double或float。
#include <iostream>
#include <cmath>
using namespace std;
const int len = 31269;
unsigned a[len];//第i组,数字序列的长度
unsigned s[len];//前i组,数字序列的长度
//打表,预先获取第2147483647个位的序列分组情况
void play_table() {
a[1] = s[1] = 1;
for (int i = 2; i < len; i++) {
//log10(i)+1 表示第i组数字列的长度 比 第i-1组 长的位数
a[i] = a[i - 1] + (int)log10((double)i) + 1;
s[i] = s[i - 1] + a[i];
}
return;
}
//计算序列第n个位置上的数字
int compute(int n) {
int i = 1;
while (s[i] < n)
i++;//确定第n个位置,出现在第i组
int pos = n - s[i - 1];//pos为第n个位置 在 第i组中的下标值
int tmp = 0;//第i组(n所在的组)的长度
for (i = 1; tmp < pos; i++)
tmp += (int)log10((double)i) + 1;
/*
* 1.i-1,刚好等于第n位个置上的数
* 2.len-pos就是第i组中pos位置后多余的数字位数
* 要取出pos位上的数字,利用(i-1)/pow(10,len-pos),先删除pos后多余的数字
* 再对剩下的数字取模,就可以得到pos
*/
return (i - 1) / (int)pow((double)10, tmp - pos) % 10;
}
int main() {
play_table();
int t,n;
cin >> t;
while (t--) {
cin >> n;
cout << compute(n) << endl;
}
return 0;
}