lintcode算法试题
题目:
1256. Nth Digit
Find the nth
digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
样例
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.
思路:开始很笨,想到的思路超过内存限制,参考下面连接的思路,分区间,逐区间查找,需要3个变量辅助,变量length代表区间内每个int中数字个数,默认从1开始,每次更新加1,(1-10,10-100,100-1000),变量cnt代表当前区间内int的个数,默认是9(1-9,10-99,100-999),每次更新*10,每个区间内数字的个数为length*cnt,如果给出的int超过这个区间内的数字,那么就查找下一个区间,直到找到所在区间;start代表区间内对应的int,初试为1 每次更新*10;找到区间后找到对应的int方法是start + int((n-1)/length)(初试坐标+偏置项),转化为str,该int的(n-1)%length上数为所求数。
class Solution: """ @param n: a positive integer @return: the nth digit of the infinite integer sequence """ def findNthDigit(self, n): # write your code here cnt = 9 length = 1 start = 1 while n > cnt*length: n -= cnt*length length += 1 cnt *= 10 start *=10 start += (n - 1) / length t = str(start) return int(t[(n - 1) % length])
参考 http://www.cnblogs.com/grandyang/p/5891871.html