POJ1019

给定一个正整数i,程序需要找到序列S1S2...Sk中位置i的数字。每个Sk是1到k的连续正整数序列。例如,前80个数字是112123...。输入包含测试用例的数量t和每个测试用例的整数i。输出是每个测试用例中位置i的数字。解决思路涉及对数函数log10()来确定数字的位数,通过一系列转换和计算找到目标数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

思路:头一次见到用log10()函数(对数函数)求一个数字的位数(题做得太少)。

先求出各个序列的长度,然后将该序列转到最后一个序列中(转化到1234567891011....这样的序列里),然后确定其再该序列的位置,利用log10(),求出这个位置对应的数字和在该数字的第几位,然后number/pow(10,在该数的位置)%10就可以求出来了

#include<iostream>
#include<string.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const long long INF = 2147483647L;
const int MAX = 100000;
long long num[MAX];
long long sum[MAX];
int n;

/*num[i]
i = 1  1        1
i = 2  12       2
i = 3  123      3
i = 4  1234     4
i = 4  12345    5
*/
void init()
{
    num[0] = 0; sum[0] = 0;
    for (int i = 1; ; i++)
    {
        num[i] = num[i-1] + (int)log10((double)i) + 1;
        sum[i] = sum[i-1] + num[i];
        if (sum[i] >= INF)
            break;
    }
}

int cal(int n)
{
    int i = 1;
    for(;;i++)
    {
        if (sum[i] >= n)
            break;
    }
    int pos = n - sum[i-1];//当前序列长度(从1开始的序列)
    int len = 0;
    int number = 1;//pos所在位置对应的数
    for (number = 1; ;number++)
    {
        len += (int)log10((double)number) + 1;
        if (len >= pos)
            break;
    }
    len = len - pos;    //当前数字的位置(从左往右数)
    return ((int)(number / pow(10.0, len))) % 10;
}

int main()
{
    init();
    int t;
    cin >> t;

    while (t--)
    {
        int i;
        cin >> i;
        cout << cal(i) << endl;
    }

    return 0;
}







 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值