leetcode_400. Nth Digit 查找自然数序列中的第n个数字
2016-11-05 17:15
357 查看
题目:
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:
Example 2:
题意:
在自然数的序列1,2,3,4,5,……中,给定数字n,写一个函数,返回这个序列的第n个数字
代码:
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
if n > 0 :
k = 1 #k:记录n对应的数字的位数
while n > k*9*10**(k-1) :
n -= k*9*10**(k-1)
k += 1
if n%k == 0 : #t:记录n为第k位上的第几个数
t = n/k
else :
t = n/k + 1
num = 10**(k-1) + t -1 #num:记录n对应的十进制数
temp = n-(t-1)*k #temp:记录n对应十进制数num上的第几个数字
num_list = [] #将num各个数字分解到num_list中
while num/10 > 0 :
num_list.append(num%10)
num = num/10
num_list.append(num)
num_list = num_list[::-1]
return num_list[temp-1] #返回num中的第temp个数字
笔记:
思路:根据自然数中各个数的数字长度规律,由n推导出n对应自然数序列中的哪个数,以及这个数中的哪个数字,然后将这个数字返回
自然数序列中各个数的数字分布:
1-9: 1*9
10-99: 2*90
100-999: 3*900
个人感觉这个题很无聊,推导过程很繁琐,对应中间变量多,精准度要求很高。
这个题不是我喜欢的类型。
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.
题意:
在自然数的序列1,2,3,4,5,……中,给定数字n,写一个函数,返回这个序列的第n个数字
代码:
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
if n > 0 :
k = 1 #k:记录n对应的数字的位数
while n > k*9*10**(k-1) :
n -= k*9*10**(k-1)
k += 1
if n%k == 0 : #t:记录n为第k位上的第几个数
t = n/k
else :
t = n/k + 1
num = 10**(k-1) + t -1 #num:记录n对应的十进制数
temp = n-(t-1)*k #temp:记录n对应十进制数num上的第几个数字
num_list = [] #将num各个数字分解到num_list中
while num/10 > 0 :
num_list.append(num%10)
num = num/10
num_list.append(num)
num_list = num_list[::-1]
return num_list[temp-1] #返回num中的第temp个数字
笔记:
思路:根据自然数中各个数的数字长度规律,由n推导出n对应自然数序列中的哪个数,以及这个数中的哪个数字,然后将这个数字返回
自然数序列中各个数的数字分布:
1-9: 1*9
10-99: 2*90
100-999: 3*900
个人感觉这个题很无聊,推导过程很繁琐,对应中间变量多,精准度要求很高。
这个题不是我喜欢的类型。
相关文章推荐
- Leetcode 400. Nth Digit 第n个数字 解题报告
- leetcode 400. Nth Digit 从1到n第n位数字是什么 + 找规律
- 400. Nth Digit (找第n个数字)
- LeetCode 400. Nth Digit
- Leetcode 400. Nth Digit[easy]
- leetcode 209. Minimum Size Subarray Sum-子序列最小长度|双指针|二分查找
- 【Leetcode】400. Nth Digit
- 数字统计(LeetCode Number of digit One)
- LeetCode 400. Nth Digit
- leetcode 400. Nth Digit解题报告
- 400. Nth Digit (leetcode) 。。。
- (hdu step 4.1.5)find the nth digit(求S串中的第n个位置上是什么数字)
- 【leetcode 移除有序序列重复数字】Remove Duplicates from Sorted Array(List) I(II)
- LeetCode 400. Nth Digit
- LeetCode 400. Nth Digit
- [LeetCode]--400. Nth Digit
- [分析总结:leetcode-Number of Digit One]寻找整数1到n之间所有数字中1出现的次数
- [LeetCode] Number of Digit One 数字1的个数
- LeetCode 31 Next Permutation 寻找一个数字序列的比他大的最小序列
- [leetcode] 400. Nth Digit 解题报告