Number Sequence
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
题意:
给出的字符串是1 12 123 1234 ……这样规律的字符。求出第k个字符。
代码如下:
#include<stdio.h>
#include<stdlib.h>
int s[11], a[11], b[200000];
//数组s存取i位数的位数和,a[i] 是1, 10, 100, 1000……这样可以方便求出1位数个数是10-1个,2位数个数100-10个。
void set()
{
int i, p, pre;
for (i = 1, p = pre = 1; i <= 8; i++)
{
a[i] = p;
p *= 10;
s[i] = (p - pre) * i;
pre = p;
}
}
void setLen()
{
int i, j, t;
for (i = 1, j = 1, b[0] = 0, t = 10; b[i-1] < 1000000; i++)
{
if (i == t)//如果i是10的幂次方。表示接下来的数的位数都增加一位
{
t *= 10;
j++;
}
b[i] = b[i-1] + j;
}
}
int cut(int len)//寻找len的所在的阶段n,切去前n-1段的位数和,剩下的就是len在第n段的位数。
{
int i;
for (i = 1; len > b[i] ; len -= b[i], i++);
return len;
}
int location(int num, int len)//求数字num里的第len个数字。
{
int i, c[10];
for (i = 0; num; i++)
{
c[i] = num % 10;
num /= 10;
}
return c[i-len];
}
void deal(int m)
{
int i, t, num, result;
m = cut(m);
for (i = 1; i <= 8; i++)
{
if (m > s[i])
{
m -= s[i];//减去i位数的位数和。
}
else
{
//求出m在i位数里排在第几。
t = m % i;
m /= i;
num = a[i] - 1 + m;
if (t)//如果t == 0,表示第m个数恰好是num的个位,即第i个数;否则num++;
{
num++;
result = location(num, t);
}
else
{
result = location(num, i);
}
break;
}
}
printf("%d\n", result);
}
void read()
{
int n, m;
scanf("%d", &n);
while (n--)
{
scanf("%d", &m);
deal(m);
}
}
int main()
{
int n;
set();
setLen();
read();
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define maxn 40000
int a[maxn], s[maxn];
void set()
{
int i;
for (i = 1, a[i] = 0, s[i] = 0; i < 40000;i++)
{
a[i] = (int)log10(double(i) * 1.0) + 1;//求i的位数。
s[i] = s[i-1] + a[i];//每一阶段的位数
}
}
void deal(int len)
{
int i;
for (i = 0; len > s[i]; len -= s[i], i++);
for (i = 1; len > a[i]; len -= a[i], i++);
printf("%d\n", i / (int)pow(10, (double)(a[i] - len)) % 10);
}
int main()
{
int n, len;
set();
scanf("%d", &n);
while (n--)
{
scanf("%d", &len);
deal(len);
}
return 0;
}