hdu Problem - 1597 find the nth digit

    技术2022-05-20  42

     

    find the nth digit

     

    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

     

    水题

     

    由假设观察可得:S = S1 + S2 + S3 + ... + Sm = m*(m+1)/2 

    定义a为 第n个数 属于字符串Sa,此题关键在求a。

    很明显:

         a*(a-1)/2  < n    (n的序号大于前S(a-1)的和)

         a*(a+1)/2 >= n   (n的序号小于前Sa的和)

     

    两种方法求a:

     

    《1:

    暴搜

     

    《2:

    由式子:a*(a+1)/2 >=  n >a*(a-1)/2 可以看出

    对2*n开方的话 结果与a非常接近 开放后稍作加减便可找到a

     

     

    求出a后 定义 b= n - a*(a-1)/2 为第n个数在字符串Sa中的序号

     

    b%9后  如果结果等于0的话输出9  否则直接输出结果就对了

     

     

    #include <iostream> #include <cmath> using namespace std; int main() { int a; cin >> a; while (a--) { long long m,n; cin >> n; m =(long long) sqrt(n*2); // cout << " m*(m+1)/2 " << m*(m+1)/2 <<endl; // cout << " m" << m <<endl; if (m*(m+1)/2 >n) { while (m*(m+1)/2 >n) m--; int temp = (n-m*(m+1)/2 )%9; if (temp==0)cout << "9"<<endl; else cout <<temp <<endl; } else if (m*(m+1)/2 <n) { while (m*(m+1)/2 <n) m++; long long temp = (n-m*(m-1)/2 )%9; if (temp==0)cout << "9"<<endl; else cout <<temp <<endl; } else { long long temp = (n-m*(m-1)/2 )%9; if (temp==0)cout << "9"<<endl; else cout <<temp <<endl; } } return 0; }  

     

     

     


    最新回复(0)