Number Sequence
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 37890 | Accepted: 10952 |
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
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
题意: 在一个数列中找出处于第n个位置的元素,元素范围[0,9],
数列是有一定规律的:
1
12
123
1234
12345
......
以这个规律排列下去
#include <iostream> #include <stdio.h> #include <string.h> #include <algorithm> using namespace std; long long int a[320000]; long long int sum[320000]; int b[10]; int main() { a[1]=1; sum[1]=1; for(int i=2; i<320000; i++) // 把前i个数分为一组,a[i]与a[i-1]只差一个数, //但是差的个数是他们的位数,如果三位数就是差三,依次类推 { if(i>=2&&i<10)a[i]=a[i-1]+1; else if(i>=10&&i<100)a[i]=a[i-1]+2; else if(i>=100&&i<1000)a[i]=a[i-1]+3; else if(i>=1000&&i<10000)a[i]=a[i-1]+4; else if(i>=10000&&i<100000)a[i]=a[i-1]+5; else a[i]=a[i]+6; sum[i]=sum[i-1]+a[i]; //把前i组个数总数统计在sum[i]数组中 } //printf("%lld\n",sum[319999]); int t; scanf("%d",&t); while(t--) { long long int n; scanf("%lld",&n); int k=lower_bound(sum+1,sum+319999,n)-sum; //先在sum数组找到>=n的下标,相当于找到在第几组 if(sum[k]==n) //如果刚好相等说明在这组中的数都在n内,而第n个刚好就是k的最低位 { printf("%d\n",k%10); //直接输出最低位就行 } else { int ki=k-1; int si=n-sum[ki]; //需要查找的与当前全部在n内的做差,即在k组存在剩余的那一部分 int kk=lower_bound(a+1,a+1+k,si)-a; //在a数组中查找到>=si 的kk //printf("kk=%d\n",kk); if(a[kk]==si) //如果查找到的等于所差的个数,那么kk组的全部元素都在n范围内且刚好, { printf("%d\n",kk%10); //输出kk的最低位 } else { int j=0; int s=si-a[kk-1]; //kk的 一部分元素在查找范围内 while(kk) { b[++j]=kk%10; kk/=10; } printf("%d\n",b[j-s+1]); //反向进入数组,即反向输出 } } } return 0; }