lintcode算法试题

题目:

1256. Nth Digit

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

样例

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.


思路:开始很笨,想到的思路超过内存限制,参考下面连接的思路,分区间,逐区间查找,需要3个变量辅助,变量length代表区间内每个int中数字个数,默认从1开始,每次更新加1,(1-10,10-100,100-1000),变量cnt代表当前区间内int的个数,默认是9(1-9,10-99,100-999),每次更新*10,每个区间内数字的个数为length*cnt,如果给出的int超过这个区间内的数字,那么就查找下一个区间,直到找到所在区间;start代表区间内对应的int,初试为1 每次更新*10;找到区间后找到对应的int方法是start + int((n-1)/length)(初试坐标+偏置项),转化为str,该int的(n-1)%length上数为所求数。


class Solution:
    """
    @param n: a positive integer
    @return: the nth digit of the infinite integer sequence
    """
    def findNthDigit(self, n):
        # write your code here
        cnt = 9 
        length = 1 
        start = 1 
        while n > cnt*length:
            n -= cnt*length
            length += 1  
            cnt *= 10 
            start *=10 
        start += (n - 1) / length
        t = str(start)
        return int(t[(n - 1) % length])

 

 

 

 

 

 

 

参考 http://www.cnblogs.com/grandyang/p/5891871.html

转载于:https://www.cnblogs.com/ai-fish/p/9199181.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值