您的位置:首页 > 其它

400. Nth Digit

2016-11-29 21:36 113 查看
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.


这是一个纯数学的问题,问第n个digit是什么。

举例说明:如果n=250,则问的是第250个digit是什么?

类似一个小学生的数学竞赛题,甚至更简单。

分步骤来进行:

1. 先判断第250个digit,对应的数是几位数?

1. 对应的数到底是哪个?

1. 对应是这个的数的第几位?

- 一位数9个 二位树 90个,一共9+90*2个digit,250-9-90*2=61,所以,250对应的是三位数

- 61除3得20,余1;所以第二部,对应的是100(第零个)+20=120

- 余下的1,就表示是120的第一位1

同理:

n=251 最后余2,第2位120;n=252,得63除3得21余0,就是121的前一个digit,即0。

class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
dig=1#先假定是一位数
#第一步
while n-dig*9*10**(dig-1)>0:
n-=dig*9*10**(dig-1)
dig+=1
#第二步
number,wei=10**(dig-1)+n//dig,n%dig
#第三步
if not wei:
return (number-1)%10
else:
return int(str(number)[wei-1])


第一步的计算稍微改进一下:

class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
dig=1#先假定是一位数
base=9
while n-dig*base>0:
n-=dig*base
base*=10
dig+=1

number,wei=10**(dig-1)+n//dig,n%dig

if not wei:
return (number-1)%10
else:
return int(str(number)[wei-1])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode