LeetCode 400. Nth Digit

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:
3

Output:
3

 

Example 2:

Input:
11

Output:
0

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.

 


题目标签:Math

  题目给了我们一个 number n,让我们找到 第n个 digit。

  首先来看一下规律:

       start - range    len

number  1 - 9                            1 digit

      10 - 99                        2 digits

      100 - 999                    3 digits

      ...

 

  想法是,首先我们要找到 第n个 digit 是在哪一个 range 里的,然后通过计算找出digit。

  我们从1 - 9 开始,这里有 9 个digits,如果 n 大于 9,那么digit 肯定在更大的 range 里,继续loop。

  我们需要初始 len = 1; range = 9; start = 1;

  len 是一个个的增加;

  range 是 10倍的增加, 1-9 是 9个; 10 - 99 是 90个;100 - 999 是 900个 ... 

  start 也是 10倍的增加,1, 10, 100 ... 

  当我们找到具体在哪一个 range 里之后,可以利用 (n-1) / len + start 来找到具体的 number;

  在利用 (n-1) % len 来找到具体的 digit。

  

 

 

Java Solution:

Runtime beats 91.87% 

完成日期:06/16/2017

关键词:math

关键点:用 / 来找到number;用 % 来找到 digit

 1 class Solution 
 2 {
 3     public int findNthDigit(int n) 
 4     {
 5         // initial vars
 6         long len = 1; 
 7         long range = 9;
 8         long start = 1;
 9         
10         while(n > (len * range)) // find n is in which range
11         {
12             n = n - (int)len * (int)range;  // minus the current total range digits
13             // move to next range
14             len++;
15             range *= 10;
16             start *= 10;
17         }
18         
19         // now is in the correct range
20         start = start + (n-1) / len;    // find the number
21         String num = "" + start;
22         int d = num.charAt( (n-1) % (int)len ) - '0';
23         
24         return d;
25     }
26 }

参考资料:http://www.cnblogs.com/grandyang/p/5891871.html

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2018-02-06 08:55  Jimmy_Cheng  阅读(153)  评论(0编辑  收藏  举报