Digit Problem

Digit Problem

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 3
描述
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
输入
The first line of the input file contains a single integer t (1 ≤ t ≤ 20), 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

//将数据分为一个个元组   1 12 123 1234 。。。

#include <stdio.h>
#include <math.h>

const int MAX_SIZE = 31269;

long long num[MAX_SIZE], sum[MAX_SIZE];

void initTable()
{
    num[1] = sum[1] = 1;
    for(int i = 2; i < MAX_SIZE; i++)
    {
        num[i] = num[i-1]+(int)log10((double)i)+1;   //第i组数的位数
        sum[i] = sum[i-1]+num[i];                     //前i组数的总位数
    }
}

int solve(int n)
{
    int i = 0, pos, cnt;
    while(sum[i] < n)                 //找到第n为所在的元组
    {
        i++;
    }
    pos = n-sum[i-1];                  //找到第n位在第i个元组里的所在位数

    cnt = 0;
    for(i = 1; cnt < pos; i++)         //i表示真实的数, cnt表示数i排到了多少位
    {
        cnt += (int)log10((double)i)+1;   
    }
    return (i-1)/(int)pow((double)10.0, (cnt-pos))%10;   //找到所在位的值
}

int main()
{
    int t, n;
    initTable();
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        printf("%d\n", solve(n));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值