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
uglysolution :)
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
相关文章推荐
- leetcode_400. Nth Digit 查找自然数序列中的第n个数字
- 【leetcode】400. Nth Digit(Python & C++)
- [LeetCode]400. Nth Digit(规律)
- leetcode 400. Nth Digit
- [leetcode] 400. Nth Digit 解题报告
- LeetCode—400. Nth Digit
- 【Leetcode】400. Nth Digit
- [LeetCode]--400. Nth Digit
- LeetCode-400. Nth Digit
- leetcode 400. Nth Digit
- LeetCode 400. Nth Digit
- 400. Nth Digit (leetcode) 。。。
- [leetcode: Python]400. Nth Digit
- [LeetCode]400. Nth Digit
- Leetcode 400. Nth Digit 第n个数字 解题报告
- LeetCode 400. Nth Digit
- 【LeetCode】 400. Nth Digit
- LeetCode | 400. Nth Digit 数学原理题
- (Leetcode)400. Nth Digit
- LeetCode 400. Nth Digit