【问题描述】
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
55
【样例输出】
2
10
题目大意
有一串数字串,其规律为
1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910 1234567891011 123456789101112······k
第一行输入有几组数据,之后几行输入位置n,
,计算这一串数字第n位是什么数,例如12345678910的第10位是10,输出每组结果
思路
将这一串数字,模拟分组,把1看做第1组,12看做第2组,123看做第3组……那么第i组就是存放数字序列为 [1,i]的正整数,容易知道第i组的长度为i,前i组的长度和满足等差数列前 i 项和公式(Si=(i*i+i)/2),想要找到位置n处的数先要找到他在哪个组(第一个Si不小于n的组),然后用n减去Si-1得到的差就是我们要的结果
实现代码1
#include <stdio.h>
int f(int n);
int main()
{
int i,m = 1,n;
scanf("%d",&n);//测试组数
for(int ni=0;ni<n;ni++)
{
scanf("%d",&i);
while (f(m) < i)//求所在组
m++;
printf("%d\n", i - f(m - 1));//输出结果
}
return 0;
}
int f(int n)//求等差数列前n项和
{
int sum=0;
for(int i=n;i>=1;i--)
sum+=i;
return sum;
}
实现代码2
#include<stdio.h>
int f(int i)//求等差数列前n项和
{
int s;
s=(i*i+i)/2;
return s;
}
int main()
{
int a,d,n,s[9999],i;
scanf("%d",&a);
for(i=1;i<=a;i++)
{
scanf("%d",&d);
n=1;
while(f(n)<d)//求所在组
n++;
s[i]=d-f(n-1);
}
for(i=1;i<=a;i++)
{
printf("%d\n",s[i]);
}
return 0;
}