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
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)
There should be one output line per test case containing the digit located in the position i.
2 8 3
2 2
每个小序列的长度也好求,用数组sum[]存每层的长度,sum[i]=sum[i-1]+i的位数;因为每一层都是上一层增加来的所以只需要存最后一层就可以然后计算出第x个数是第几层的第几个;
看看代码吧;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <algorithm>
#define MAX 200000 //这里准确来说应该是145229;原因下边再说
using namespace std;
int dp[MAX]; //存最后一层;
int sum[M,,AX]; //每一层的长度;
//2147483647 //注意这个数,这是题目给的界限;此数也是int型的最大值;
//2147378477 //这个数是 第31267层最后一个数在总序列中的位置, 而 第31267层的长度为145229;如果是第31268层,则超出int型范围;
int main(){
int t;
int c=0;
sum[0]=0; //第0层为0;
for(int i=1; i<=31267; i++){ //1-31267层,每层的长度;
int j=0;
int x=i;
int b[10];
while(x>0){
b[j]=x%10;
x/=10;
j++;
}
sum[i]=sum[i-1]+j;
for(j--; j>=0; j--)
dp[++c]=b[j]; //储存第31267层;
}
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
int ans=0;
int i;
for(i=1; i<=31267; i++){ //找到第n 个数的层数;
ans+=sum[i];
if(ans>=n) break;
}
if(ans>=n) ans-=sum[i];
int k=n-ans; //k表示n所在层数第k个数;
printf("%d\n",dp[k]); //输出;
}
}
本文介绍了一个算法问题,即在一个由连续数字序列组成的无限序列中,如何找出特定位置上的数字。文章详细解释了如何通过计算各段序列的长度来确定目标数字位于哪个序列段内,并给出了完整的C++实现代码。
&spm=1001.2101.3001.5002&articleId=77371785&d=1&t=3&u=2833876df1d0420b8b9814fc6d70e371)
2万+

被折叠的 条评论
为什么被折叠?



