Number Sequence
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 37890 | Accepted: 10952 |
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
这个题就是给你一个很神奇的数列,(详情请看题面),然后输入t组数据,每组一个数x,问你第x位上的数字是几?
注意!数列虽然是能从1~排到10但是这个“10”是占两个数位的!!!。
规律很好看的就是1...1 2...123...1234...12345.....这样一直下去。
思路:
1.我们把这一个大长串分成这样的小串,用一个数组记录长度,a[i]用来记录12345..i的串的长度,然后用b[i]表示a[1]+a[2]+...a[i]的总长度。
2.我们读入x的时候先找到x所在的i区间,也就是找到x是在1....到几的这个小串内。
3.然后x减去b[i]累加的,答案就是在这个小串内x位置的数。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN=31268+10;
const long long inf=2147483647;
int a[MAXN];
long long b[MAXN];
void get()
{
int i;
int x=10,cnt=1;
for(i=1;;++i)
{
if(i<x)a[i]=a[i-1]+cnt;//小于10的话长度为1
else
{
x*=10;//位数每增加1,相应的长度增加1
cnt++;
a[i]=a[i-1]+cnt;
}
b[i]=b[i-1]+a[i];//累加
if(b[i]>=inf)//数据给定的范围是inf,要先打表计算i的范围来开数组
{
break;
}
}
}
int main()
{
int i;
get();//打表
int t;
scanf("%d",&t);
long long x;
while(t--)
{
scanf("%lld",&x);
for(i=1;;++i)//先找到在哪个小串中
{
if(b[i]<=x&&b[i+1]>x)break;
}
x-=b[i];
if(!x)printf("%d\n",i%10);//如果正好是这个串的末尾
else//否则就是在下一个串中
{
int pos=i+1;//这个串就是由123456...i+1组成的
int p=10,cnt=1;
for(i=1;i<=pos;++i)
{
if(i<p)x-=cnt;//仿照上面
else
{
p*=10;
cnt++;
x-=cnt;
}
if(x<=0)break;//找到目标值了
}
cnt=1;
while(x)//每多减去一位,都要先去掉相应的位数
{
cnt*=10;
x++;
}
printf("%d\n",(i/cnt)%10);
}
}
return 0;
}