Leetcode 400.第n個數

第n個數

在無限的整數序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 個數字。git

注意:
是正數且在32爲整形範圍內 ( n < 231)
ide

示例 1: spa

輸入: 字符串

3 it

 

輸出: io

3 class

示例 2: di

輸入: view

11 vi

 

輸出:

0

 

說明:

11個數字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 裏是0,它是10的一部分。

 

 1 public class Solution {
 2     /**
 3      * 這裏是找第n個數字(這裏的數和數字有區別,數字能夠理解爲將全部數拼合成一個字符串後的第n爲對應的數字(0-9))
 4      * 這裏首先分析一下位數和規律
 5      * 個位數:1-9,一共9個,共計9個數字
 6      * 2位數:10-99,一共90個,共計180個數字
 7      * 3位數:100-999,一共900個,共計2700個數字
 8      * 4位數,1000-9999,一共9000個,共計36000個數字
 9      * 以此類推,
10      * 這樣咱們就能夠首先定位到是哪一個數,再找到其對應的數字
11      * */
12 
13     public int findNthDigit(int n) {
14         //當心溢出
15         int digitType = 1;
16         long digitNum = 9;
17         //定位到是幾位數
18         while(n > digitNum*digitType){
19             n -= (int) digitNum*digitType ;
20             digitType++;
21             digitNum*=10;
22         }
23         //定位到是這些幾位數裏面的第幾個的第幾位
24         int indexInSubRange = (n -1) / digitType;
25         int indexInNum = (n -1) % digitType;
26         //還原數字
27         int num = (int)Math.pow(10,digitType - 1) + indexInSubRange ;
28         int result = Integer.parseInt((""+num).charAt(indexInNum)+"");
29         return result;
30     }
31 }
相關文章
相關標籤/搜索