POJ1019——Number Sequence(大数处理)

时间:2023-12-28 15:45:20

Number Sequence

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
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

题目大意:

    给定一个字符串,构成如下:

    1121231234...123456789101112...12345678910111213..N

    问字符串的第i位是多少。

解题思路:

    将字符串划分成N段。

    1 12 123 1234 ... 1234567891011 ... 123456789101112....N

    那么对于第K段的长度len[k]=len[k-1]+K这个数字的长度。即len[k]=len[k-1]+log10(k)+1。

    再定义sum[k]=sum[k-1]+len[k]。通过比较sum[]与i的大小即可定位到i所在的字段。

    假设i在第k个字段(1234567...t....k)中,那么i-sum[k-1]表示的就是i在第k个字段中的位置。

    再通过公式log10(j)+1就能判断出i所在的t和在t中的位置pos。

    ans=t/pow(10,pos)%10。

Code:

 /*************************************************************************
> File Name: poj1019.cpp
> Author: Enumz
> Mail: 369372123@qq.com
> Created Time: 2014年11月08日 星期六 02时33分13秒
************************************************************************/ #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<list>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#include<cmath>
#include<bitset>
#include<climits>
#define MAXN 40000
using namespace std;
long long len[MAXN],sum[MAXN];
void init()
{
for (int i=;i<MAXN;i++)
{
len[i]=len[i-]+(int)log10((double)i)+;
sum[i]=sum[i-]+len[i];
}
}
int solve(int N)
{
int i=;
while (sum[i]<N)
i++;
N-=sum[i-];
int len_k=,t;
for(t=;len_k<N;t++)
len_k+=(int)log10((double)t)+;
int pos=len_k-N;
return (t-)/(int)pow((double),pos)%;
}
int main()
{
int T;
cin>>T;
int N;
init();
while (T--)
{
cin>>N;
cout<<solve(N)<<endl;
}
return ;
}