ACM-Number Sequence

P - Number Sequence

A single positive integer i is given. Write a program to find the digit located in the position i in the sequence of number groups S1S2...Sk. Each group Sk consists of a sequence of positive integer numbers ranging from 1 to k, written one after another.

For example, the first 80 digits of the sequence are as follows:

11212312341234512345612345671234567812345678912345678910123456789101112345678910

Input

The first line of the input file contains a single integer t (1 ≤ t ≤ 10), the number of test cases, followed by one line for each test case. The line for a test case contains the single integer i (1 ≤ i ≤ 2147483647)

Output

There should be one output line per test case containing the digit located in the position i.

Sample Input

2

8

3

Sample Output

2

2

Code:

#include<iostream>
#include<math.h>
#define ull unsigned long long 
const int maxn=31269;
ull a[maxn];
ull s[maxn];
void init(){
	a[1]=s[1]=1;
	for(int i=2;i<maxn;i++){
		a[i]=a[i-1]+(int)log10((double)i)+1;//记录比前个数列多了多少位 
		s[i]=s[i-1]+a[i];//记录的是总位数的信息 
	}
}
int solve(int n){
	int i=1;
	while(s[i]<n) i++;//找到最接近n的总位数 
	int pos=n-s[i-1];//从1开始 
	int len=0;
	for(i=1;len<pos;i++)
		len+=(int)log10((double)i)+1;//同上差不多开始计数,计算位数 
	printf("i-1:%d,len-pos:%d",i,len-pos);
	return (i-1)/(int)pow((double)10,len-pos)%10;//逆回计数 
}
int main(){
	int T,n;
	init();
	scanf("%d",&T);
	while(T--){
		scanf("%d",&n);
		printf("%d\n",solve(n));
	} 
	return 0;
}

具体的代码如上
思路就是用一个log10对数来返回数的位数,a数组用来保持一个数串的位数,s数组用来保存总的位数,然后思路就是先找到最接近n的位数,然后一个一个找就行,大大节省了时间。

posted @ 2020-11-05 22:34  Dios314  阅读(130)  评论(0)    收藏  举报