0
点赞
收藏
分享

微信扫一扫

hdu 1597 find the nth digit(等差求和+二分)


find the nth digit


Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9045    Accepted Submission(s): 2586



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


 



Author


8600
题目分析:
可以得知第n个串长度为n,所以总长度为n(n+1)/2,那么我们找到完整的串,然后减掉,只剩下下一个不完整的,对9取模,就能得到要求的数字

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;

typedef long long LL;

int t;
LL n;

int mod[11] = {9,1,2,3,4,5,6,7,8};

LL f ( LL x )
{
    return x*(x+1)/2;
}

LL search ( LL n )
{
    LL left = 1 , right = n , mid;
    while ( left != right )
    {
        mid = (left + right+1) >> 1;
        if ( f(mid) > n ) right = mid-1;
        else left = mid;
    } 
    return left;
}

int main ( )
{
    scanf ( "%d" , &t );
    while ( t-- )
    {
        scanf ( "%lld" , &n );
        LL x = search ( n );
        if ( f(x) == n ) printf ( "%d\n" , mod[x%9] );
        else
        {
            x = n - f(x);
            printf ( "%d\n" , mod[x%9] );
        }
    }
}




举报

相关推荐

0 条评论