您的位置:首页 > 其它

LeetCode 400. Nth Digit

2016-11-07 23:17 309 查看

Problem Statement

(Source) 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.


Tags:
Math
.

Solution

首先要确定包含目标位置的数字的整数有几位数 (x)。求出这个
x
后,知道最小的x位数是多少了,而且可以求出最小的 x位数之前已经用了多少位数字。最后根据偏移量确定目标。

An
ugly
solution :)

class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
if n < 9:
return n

total = 9
digits, times = 1, 9
start = 9
while n > total:
digits += 1
times *= 10
total += digits * times
start = start * 10 + 9
total -= digits * times
times /= 10
digits -= 1
start = (start - 9) / 10
offset = (n - total) / (digits + 1)
x = start + offset
y = x + 1
mod = (n - total) % (digits + 1)
if mod == 0:
return x % 10
else:
return int(str(y)[mod-1])


A much more concise solution by StefanPochmann:

def findNthDigit(self, n):
n -= 1
for digits in range(1, 11):
first = 10**(digits - 1)
if n < 9 * first * digits:
return int(str(first + n/digits)[n%digits])
n -= 9 * first * digits
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: