acm pku 1019 Number Sequence的递归计算方法
2010-05-25 21:21
417 查看
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
:表示数字序列123…N的数字个数。
对这道题目必定有:
假设要求的数字序列的第N个数字idata时,其算法如下:
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
;
unsigned int Calc
;
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: 1019 | User: uestcshe | |
Memory: 496K | Time: 16MS | |
Language: C++ | Result: Accepted |
相关文章推荐
- 使用递归的方法计算1到100的叠加,即1+2+3+4.....+100
- python递归计算N!的方法
- 4.8 用递归方法编程计算以下式子的值: n^1+n^2+n^3+n^4+...+n^10,其中 n=1,2,3
- 递归方法,计算时间差,及sphinx(项目首页)
- C++使用递归和非递归算法实现的二叉树叶子节点个数计算方法
- 用递归方法计算整数n的阶乘n!
- 用递归方法计算n的阶乘n
- 用Python计算幂的两种方法,非递归和递归法
- 数据结构之用递归和非递归方法计算斐波那契数列的第n项
- 用递归的方法计算斐波那契数列的通项f(n),已知f1 = 1 ,f2 = 1,以后每项都是前两项的和。
- C++递归方法计算n阶行列式
- HTML:用递归的方法计算1+2+3+4...+10
- 14章类型信息-之类型转换前先做检查--之使用类字面常量--类名.class--以及动态instanceof(isInstance方法)----递归计数(计算各个类的个数)
- 用递归的方法计算第30位斐波那契数列的值
- java中递归方法的应用--计算n的阶乘
- 面试题:使用递归的方法计算1到100的累加。
- 递归方法:输入一个多位整数,计算出从0到该数1出现的个数。
- 14章类型信息-之类型转换前先做检查--之使用类字面常量--类名.class--以及动态instanceof(isInstance方法)----递归计数(计算各个类的个数)
- 用递归方法计算行列式的值
- C#递归实现显示文件夹及所有文件并计算其大小的方法