# acm pku 1019 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

Source

Tehran 2002, First Iran Nationwide Internet Programming Contest

这道题目其实就是一道数学归纳题，用递归方法可以求得其结果，为此需要如下参数：

Len[N]：表示第一次出现数字Ｎ(而不是字符串N)时，数字序列的长度。

Calc[N]：表示数字序列123…N的数字个数。

Step 1: 求出小于等于2147483647的所有Len以及相应的Calc

Step 2: 寻找Len[i]使得Len[i]<=N<Len[i+1];

Len[i]=N，则idata=i%10; 算法结束。

否则(Len[i]<N<Len[i+1]), N-=Len[i]

Step 3: 寻找Calc[i]使得Calc[i]<=N<Len[i+1];

Calc[i]=N，则idata=i%10；算法结束。

否则(Calc[i]<N<Calc[i+1])N-=Len[i], idata = i+1的第N位数；算法结束。

#include "iostream"

#include "math.h"

using namespace std;

const int N = 100000;

unsigned int Len[N];

unsigned int Calc[N];

void LenAndLen(void)

{

int i = 1;

Len[1] = 1;

Calc[1]= 1;

while(Len[i++] < 2147483647)

{

Calc[i] = Calc[i-1] + (int)floor(log10((double)i) + 1.0);

Len[i]  = Len[i-1]  + Calc[i];

}

}

int SearchData(unsigned int N)

{

int i = 1;

while(Len[i] < N)

{

i++ ;

}

if(N == Len[i])

{

return i%10;

}

else

{

N -= Len[i-1];

i = 1;

while(Calc[i] < N)

{

i++ ;

}

if(N == Calc[i])

{

return i%10;

}

else

{

N -= Calc[i-1];

return i/((int)pow(10., (double)((int)log10((double)(i*10)))-N))%10;

}

}

}

int main(void)

{

unsigned int t, n;

LenAndLen();

cin >> t;

while(t --)

{

cin >> n;

cout << SearchData(n) << endl;

}

return 0;

}

 Problem: User: Memory: 496K Time: 16MS Language: C++ Result: Accepted

• 本文已收录于以下专栏：

举报原因： 您举报文章：acm pku 1019 Number Sequence的递归计算方法 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)