本文共 1168 字,大约阅读时间需要 3 分钟。
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:3Output:3
Example 2:
Input:11Output:0Explanation: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.
思路:这道题的意思是把所有数字排列12345678910111213...,然后返回第n位的数字.
class Solution(object): def findNthDigit(self, n): """ :type n: int :rtype: int """ start = 1 size = 1 step = 9 while (n>size*step): n = n - size*step step = step * 10 start = start * 10 size = size + 1 num = str((n-1)/size + start) return int(num[(n-1)%size])
比如输入n=4590,那经过运算输出的结果n: 1701, step: 9000, start: 1000, size: 4, num: 1425 return:1
size表示现在计算的是4位数
start就是4位数的开始数字(1000)
step计算的是进入下一循环需要跨过多少数字.(4位数start是1000,5位数start是(1000+9000)=10000)
n是指'123456789101112...998999'这个字符串到数字999已经经过了(4590-1710)=2880位,接下来要计算的是从'100010011002...14241425...'中的1710位
num指的是第4590位数字1425中的某一个数字
最后的(n-1)%size确定的是数字1425中的第几位数.计算结果为0,所以是'1425'的第一位,最终返回1
转载地址:http://vprbb.baihongyu.com/