1. 程式人生 > >leetcode (Nth Digit)

leetcode (Nth Digit)

Title:Nth Dight    400

Difficulty:Easy

原題leetcode地址:   https://leetcode.com/problems/nth-digit/

 

1.   數學邏輯,找規律

時間複雜度:O(n),一次一層for迴圈,迴圈最長為n。

空間複雜度:O(1),沒有申請額外空間。

    /**
     * 數學找規律
     * @param n
     * @return
     */
    public static int findNthDigit(int n) {

        if(n <=0) {
            return 0;
        }

        long count = 9;
        int start = 1;
        int len = 1;

        while(n > len*count){
            n -= len*count;
            len++;
            start *= 10;
            count *= 10;
        }
        start += (n-1)/len;

        return String.valueOf(start).charAt((n - 1) % len) - '0';

    }