POJ1019

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;
}







猜你喜欢

转载自blog.csdn.net/qq_39479426/article/details/81546246