POJ1019——Number Sequence(大数处理)

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:

 1 /*************************************************************************
 2     > File Name: poj1019.cpp
 3     > Author: Enumz
 4     > Mail: 369372123@qq.com
 5     > Created Time: 2014年11月08日 星期六 02时33分13秒
 6  ************************************************************************/
 7 
 8 #include<iostream>
 9 #include<cstdio>
10 #include<cstdlib>
11 #include<string>
12 #include<cstring>
13 #include<list>
14 #include<queue>
15 #include<stack>
16 #include<map>
17 #include<set>
18 #include<algorithm>
19 #include<cmath>
20 #include<bitset>
21 #include<climits>
22 #define MAXN 40000
23 using namespace std;
24 long long len[MAXN],sum[MAXN];
25 void init()
26 {
27     for (int i=1;i<MAXN;i++)
28     {
29         len[i]=len[i-1]+(int)log10((double)i)+1;
30         sum[i]=sum[i-1]+len[i];
31     }
32 }
33 int solve(int N)
34 {
35     int i=1;
36     while (sum[i]<N)
37         i++;
38     N-=sum[i-1];
39     int len_k=0,t;
40     for(t=1;len_k<N;t++)
41         len_k+=(int)log10((double)t)+1;
42     int pos=len_k-N;
43     return (t-1)/(int)pow((double)10,pos)%10;
44 }
45 int main()
46 {
47     int T;
48     cin>>T;
49     int N;
50     init();
51     while (T--)
52     {
53         cin>>N;
54         cout<<solve(N)<<endl;
55     }
56     return 0;
57 }

 

posted @ 2014-11-08 09:10  Enumz  阅读(794)  评论(0编辑  收藏  举报