(HDU - 1597)find the nth digit
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13692 Accepted Submission(s): 4205
Problem Description
假设:
S1 = 1
S2 = 12
S3 = 123
S4 = 1234
………
S9 = 123456789
S10 = 1234567891
S11 = 12345678912
…………
S18 = 123456789123456789
………………
现在我们把所有的串连接起来
S = 1121231234…….123456789123456789112345678912………
那么你能告诉我在S串中的第N个数字是多少吗?
Input
输入首先是一个数字K,代表有K次询问。
接下来的K行每行有一个整数N(1 <= N < 2^31)。
Output
对于每个N,输出S中第N个对应的数字.
Sample Input
6
1
2
3
4
5
10
Sample Output
1
1
2
1
2
4
思路:预先处理出1+2+…i的和,记为sum[i],而然后利用STL中的二分查找函数,找到大于等于n的sum[i],令tmp=i-1,那么n-sum[tmp]便是当前阶有几个。具体见代码。
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=1000000;
LL sum[maxn];
int main()
{
sum[0]=0;
for(int i=1;i<maxn;i++) sum[i]=(LL)i*(1+i)/2;
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
int tmp=lower_bound(sum,sum+maxn,n)-sum-1;
n-=sum[tmp];
if(n%9==0) printf("9\n");
else printf("%d\n",n%9);
}
return 0;
}