POJ1019 ---简单的数学找规律题
Number Sequence
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 24387 | Accepted: 6534 |
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
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
题目大意就是给你这一串数字11212312341234512345612345671234567812345678912345678910123456789101112345678910……(未列完)
要我们求出第n个数是多少(从左到右看),例如第2个是1,第三个是2,第八个是2;
如果仔细观察这一串数字,可以发现他可以还分为很多小串,假设第i小串是123……i,假设第i小串所占的空间是a[i],则通过对比a[i]与a[i+1]发现,
第i+1串只比第i串多一个数,即i+1,故他们所占的空间差就是第i+1所占的空间。
对任意一个数所占的空间很好求,即 (int)log10(k)+1;
然后就可以求出每一个串的起始位置,通过与n比较就可以确定n出现在那一个串里,最后在求出n在这个串里的相对位置,就可以求出该题的解
参考代码
1 #include<iostream>
2 #include<cmath>
3 #include<cstdio>
4 using namespace std;
5 int a1[32000] ; //用来存储每一个串所占的空间
6 __int64 a[32000] ; //用来存储每一个串的起始位置
7 int num[150000]; //打印出最大的一个串
8 int main()
9 {
10 int i;
11 a1[0]=0 ;
12 a1[1]=1;
13 for ( i = 2 ; i < 32000 ; i ++ )
14 a1[i] = a1[i-1] + (int)log10(1.0*i)+1; //推导详见上文
15 a[0]=1;
16 for ( i = 1 ; i < 32000 ; i ++ )
17 a[i]=a[i-1]+a1[i-1]; //上一个串的起点加所占空间就是下一个串的起点
18 int k = 1;
19 for ( i = 1 ; i < 31300 ; i ++ )
20 {//打印最大的一个串
21 char str[20];
22
23 str[0]='0';
24 int ti = i ;
25 int len = 0 ;
26 while (ti)
27 {
28 str[len]=ti%10+'0';
29 ti=ti/10;
30 len++;
31 }
32 while ( len -- )
33 {
34 num[k]=str[len]-'0';
35 k++;
36 }
37 }
38 int t;
39 cin >> t;
40 while ( t-- )
41 {
42 int mn;
43 cin >>mn;
44 for ( i =1; i < 32000 ; i ++ )
45 if ( a[i]>=mn )
46 break;
47 if ( a[i] ==mn )
48 cout<<1<<endl;
49 else
50 {//mn-a[i-1]+1就是其在第i-1个串里的相对位置
51 cout<<num[mn-a[i-1]+1]<<endl;
52 }
53 }
54 return 0;
55 }
作者:ACShiryu
出处:http://www.cnblogs.com/ACShiryu/
若非注明,本博客文章均为原创,版权归作者和博客园共有,欢迎转载,但必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
该文章也同步发布在我的新浪微博中-ACShiryu's weibo,欢迎收听。
分类:
POJ题解
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)