美文网首页
杭电acm1597 find the nth digit

杭电acm1597 find the nth digit

作者: cwhong | 来源:发表于2018-06-28 09:02 被阅读0次

    find the nth digit

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

    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

    Solution

    这道题可以用二分法解,但从数学角度来看这是一个等差数列问题通过数列求和公式 S = (n*(n+1))/2转换成二次方程可以求出所查的数在第几个数列

    Code

    package acm1597;
     
    /**
     * date:2017.12.09
     * author:孟小德
     * function: 杭电acm1597
     *      find the nth digit
     */
     
    import java.util.*;
     
    public class Main
    {
        public static void main(String[] args)
        {
            Scanner input = new Scanner(System.in);
     
            int NUM_OF_INQUIRE = input.nextInt();   //  查询次数;
            double N_TH;   //  查询第n个数
            double STRING_LENGTH;  //  串的长度
            int RESULT;
     
            for (int i = 0;i<NUM_OF_INQUIRE;i++)
            {
                N_TH = input.nextDouble();
                STRING_LENGTH = Math.ceil(
                    (Math.sqrt(1 + 8*N_TH)-1)/2);
                N_TH -= (STRING_LENGTH * (STRING_LENGTH - 1))/2;
                RESULT = (int)(N_TH % 9);
     
                if (RESULT == 0)
                {
                    RESULT = 9;
                }
     
                System.out.println(RESULT);
     
            }
     
            input.close();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:杭电acm1597 find the nth digit

          本文链接:https://www.haomeiwen.com/subject/emwwyftx.html