1. 程式人生 > >400. Nth Digit

400. Nth Digit

not 變量 char tar 字符串 一個 一位 要求 out

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).

Example 1:

Input:

Output:
Example 2:

Input:

Output:

Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.

這道題還是蠻有創意的一道題,是說自然數序列看成一個長字符串,問我們第N位上的數字是什麽。那麽這道題的關鍵就是要找出第N位所在的數字,然後可以把數字轉為字符串,這樣直接可以訪問任何一位。那麽我們首先來分析自然數序列和其位數的關系,前九個數都是1位的,然後10到99總共90個數字都是兩位的,100到999這900個數都是三位的,那麽這就很有規律了,我們可以定義個變量cnt,初始化為9,然後每次循環擴大10倍,再用一個變量len記錄當前循環區間數字的位數,另外再需要一個變量start用來記錄當前循環區間的第一個數字,我們n每次循環都減去len*cnt (區間總位數),當n落到某一個確定的區間裏了,那麽(n-1)/len就是目標數字在該區間裏的坐標,加上start就是得到了目標數字,然後我們將目標數字start轉為字符串,(n-1)%len就是所要求的目標位,最後別忘了考慮int溢出問題,我們幹脆把所有變量都申請為長整型的好了,參見代碼如下:

1-9 : count:9 * len:1

10-99: count:90 * len:2

100-999: count:900 * len:3

1000-9999: count: 9000 * len:4

maintain a count, len, start

public class Solution {
    public int findNthDigit(int n) {
        int start = 1;
        int len = 1;
        long count = 9;
        while (n > len*count) {
            n -= len*count;
            start *= 10;
            len ++;
            count *= 10;
        }
        start += (n-1)/len;
        char res = Integer.toString(start).charAt((n-1)%len);
        return Character.getNumericValue(res);
    }
}

  

Character.getNumericValue(res): 返回字符串表示的int 值

400. Nth Digit