400. Nth Digit

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])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值