# 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

#### poj-1019-Number Sequence【思维】【规律】

2016-11-08 22:12:09

#### poj 1019Number Sequence(数学 巧妙~~~)

2016-08-18 22:40:57

#### POJ1019:Number Sequence

2015-05-11 20:45:22

#### PKU 1019 Number Sequence

2017-12-24 23:04:12

#### poj Number Sequence 1019 （打表 &模拟）

2016-03-22 22:33:20

#### 杭电ACM 1005：Number Sequence

2015-05-15 10:08:03

#### POJ 1019 Number Sequence (循环递增序列的的第K个值)

2015-08-17 16:19:02

#### 杭电ACM1019求最大公约数

2013-03-18 18:11:12

#### [ACM]Number Sequence

2013-09-01 12:48:11

#### pku 1019 Number Sequence(逐步求精)

2009-08-11 19:33:00