Number Sequence
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 30421 | Accepted: 8520 |
Description
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
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
题意:有一串数字串,其规律为
1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910 1234567891011 123456789101112······k
输入位置n,计算这一串数字第n位是什么数字,注意是数字,不是数!例如12345678910的第10位是1,而不是10,第11位是0,也不是10。总之多位的数在序列中要被拆分为几位数字,一个数字对应一位。
思路:分组,把1看作第一组,12看作第二组,123看作第三组,...以此类推。
规律:第i组数字列的长度比第i-1组的长度大log10(i)+1。
给出一个位置n,先找出n在所对应组的下标pos,如8在所对应组的下标pos为2.再找出这个组中包括下标为pos的数,在这个数中取最终结果,详细见代码.
AC代码:
#include <cstring> #include <string> #include <cstdio> #include <algorithm> #include <queue> #include <cmath> #include <vector> #include <cstdlib> #include <iostream> using namespace std; long long a[31269]; //保存第i组的序列长度 long long s[31269]; //保存前i组的序列长度 void table() { s[1]=1; a[1]=1; for(int i=2; i<31269; i++) { a[i]=a[i-1]+(int)log10((double)i)+1; //log10(i)+1 表示第i组数字列的长度 比 第i-1组 长的位数 s[i]=s[i-1]+a[i]; } } int main() { int t,n; table(); cin>>t; while(t--) { cin>>n; int i=1; while(s[i]<n) i++; //确定整个数字序列的第n个位置出现在第i组 int pos=n-s[i-1]; //pos表示整个数字序列的第n个位置在第i组的下标 //a[i]保存第i组的序列长度,将n所在组看成是整个数字序列时,a[i]表示下标包括pos的数前面的数的长度 i=1; while(a[i]<pos) //在n所在的组中从1开始遍历每个数 i++; //最后a[i]即为下标包括pos的数的长度,最后i即为n所在组下标包括pos的数 cout<<i/(int)pow((double)10,a[i]-pos)%10<<endl; //a[i]-pos表示i在pos位置之后长度, //i/pow(10,a[i]-pos)表示使i舍弃pos位置之后的数字 //最后mod10即为所求 } return 0; }