题目:
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.
链接:https://leetcode.com/problems/nth-digit/#/description
3/22/2017
抄答案
尝试理解过程:
1. 按照n增加的顺序来处理,而不是用lookup table或者一个式子来算。这样的好处是可以条理清晰的运用循环。
2. 方法,循环体内,每次进入循环体意味着n至少是属于这个范围或者更大的值,先把上一轮的范围的所有用到的n去掉:n -= 9 * first * digits。然后first *10(10, 100, 100),digit + 1
3. 为什么判断条件里最后有/digits?这是由在之前范围里所消耗的n值,digits代表每个范围内的数字所消耗的n。比如1230这个数占用4个值。
4. 最后一行为n所在的数和n所在的数位。
1 public class Solution { 2 public int findNthDigit(int n) { 3 n -= 1; 4 int first = 1, digits = 1; 5 while (n / 9 / first / digits >= 1) { 6 n -= 9 * first * digits; 7 first *= 10; 8 digits++; 9 } 10 return (first + n / digits + "").charAt(n % digits) - '0'; 11 } 12 }
有很多题用到了数位和9这个数,其中一个例子是
http://www.cnblogs.com/panini/p/6504897.html
应该还有更明确的使用例子,等找到了再来更新这篇博客。
其他讨论: