Number Sequence(不知道啥方法,不过做出来了,不容易啊)

本文介绍了一个算法问题,即在一个由连续数字序列组成的无限序列中,如何找出特定位置上的数字。文章详细解释了如何通过计算各段序列的长度来确定目标数字位于哪个序列段内,并给出了完整的C++实现代码。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

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
题意挺好理解的,序列有多个小序列组成,第i个序列是1-i,求第x位置上的数字是多少;如:112123123412345123456123456712345678123456789123456789101234567891011123456789101112的组成是:112123123412345123456123456712345678123456789123456789101234567891011123456789101112
每个小序列的长度也好求,用数组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]);      //输出;
    }
}






开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值