找规律-剑指 Offer 44. 数字序列中某一位的数字

143 阅读1分钟

题目链接

思路

  1. 确定数位的量级 dI64R1.md.png
    比如1525, 10.9101+20.9102+30.9103+40.9104>15251 * 0.9 * 10^{1} + 2 * 0.9 * 10^{2} + 3 * 0.9 * 10^{3} + 4 * 0.9 * 10^{4} > 1525 10.9101+20.9102+30.9103<15251 * 0.9 * 10^{1} + 2 * 0.9 * 10^{2} + 3 * 0.9 * 10^{3} < 15259+90+900+9000>1525>9+90+9009 + 90 + 900 + 9000 > 1525 >9 + 90 + 900 可见对应的digit = 3
  2. 找到所对应的num n=1525990900n = 1525-9-90-900 num=103+(n1)/3,n-1为了从1001计数num = 10^{3} + (n-1)/3,\quad \text{n-1为了从1001计数}
  3. num转为string,找到对应的下标 index=(n1)%3index = (n-1)\%3

代码实现

class Solution:
    def findNthDigit(self, n: int) -> int:
        # find the digits
        digit = 1
        count = 1
        while digit * 0.9 * pow(10, digit) < n:
            n -= digit * 0.9 * pow(10, digit) 
            digit += 1
        # find the num
        s = str(pow(10, digit-1) + (n-1)//digit)
        # find the index
        return int(s[int((n-1)%digit)])