1019. Number Sequence

本文介绍了一种程序设计方法,用于找出特定数列中任意位置的数字。该数列由一系列连续整数组成,每组包含从1到k的所有整数。通过预处理和高效查找策略,程序能在庞大的数列中快速定位并返回指定位置的数字。

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


代码

/*通过打表可以发现,一共可以分为31268个数据串。最长的一串有145236位*/
#include <iostream>
#include <math.h>
#include <string.h>

using namespace std;

int len1[31270] = { 0 };    
unsigned int len2[31270] = { 0 };     
void group()
{
    int i = 0;

    len1[1] = 1;
    len2[1] = 1;
    for (i = 2;i < 31270; i++)
    {
        len1[i] = len1[i - 1] + (int)log10(i*1.0) + 1;
        len2[i] = len2[i - 1] + len1[i];
    }
}

int main()
{
    int t = 0;
    int j = 1,k = 1;
    int MAX[145240] = { 0 }; 

    group();

    for (j = 1; j < 31270; j++)
    {
        char str[10];
        int a = 0;
        int temp;

        temp = j;
        while (temp)
        {
            str[a++] = temp % 10 + '0';
            temp /= 10;
        }             //确定最长的一串
        while (a--)
        {
            MAX[k++] = str[a] - '0';
        }
    }

    cin >> t;
    while (t--)
    {
        int num = 0, i = 0;

        cin >> i;
        for (j = 0; j < 31270; j++)
        {
            if (len2[j] >= i)
                break;
        }
        num = MAX[i - len2[j - 1]];

        cout << num << endl;
    }

    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值