博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
****LeetCode400. Nth Digit
阅读量:2241 次
发布时间:2019-05-09

本文共 1168 字,大约阅读时间需要 3 分钟。

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:3Output:3

Example 2:

Input:11Output:0Explanation: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.

思路:这道题的意思是把所有数字排列12345678910111213...,然后返回第n位的数字.

class Solution(object):    def findNthDigit(self, n):        """        :type n: int        :rtype: int        """        start = 1        size = 1        step = 9                while (n>size*step):            n = n - size*step            step = step * 10            start = start * 10            size = size + 1        num = str((n-1)/size + start)        return int(num[(n-1)%size])

比如输入n=4590,那经过运算输出的结果n: 1701, step: 9000, start: 1000, size: 4, num: 1425    return:1

size表示现在计算的是4位数

start就是4位数的开始数字(1000)

step计算的是进入下一循环需要跨过多少数字.(4位数start是1000,5位数start是(1000+9000)=10000)

n是指'123456789101112...998999'这个字符串到数字999已经经过了(4590-1710)=2880位,接下来要计算的是从'100010011002...14241425...'中的1710位

num指的是第4590位数字1425中的某一个数字

最后的(n-1)%size确定的是数字1425中的第几位数.计算结果为0,所以是'1425'的第一位,最终返回1

转载地址:http://vprbb.baihongyu.com/

你可能感兴趣的文章
阿里巴巴十年Java架构师分享,会了这个知识点的人都去BAT了
查看>>
Intellij IDEA 使用技巧一
查看>>
IDEA 护眼色设置 背景行颜色取消等设置
查看>>
idea如何显示git远程与本地的更改对比?
查看>>
Git 分支 - 分支的新建与合并
查看>>
git创建与合并分支
查看>>
23种设计模式介绍以及在Java中的实现
查看>>
如何把本地项目上传到Github
查看>>
Git的使用--如何将本地项目上传到Github
查看>>
zookeeper客户端命令行查看dubbo服务的生产者和消费者
查看>>
intellij idea 相关搜索快捷键
查看>>
oracle查看数据库连接池中最大连接数和当前用户连接数等信息
查看>>
oracle中创建同义词(synonyms)表
查看>>
建立DB-LINK和建立视图
查看>>
普通视图和物化视图的区别(转)
查看>>
物化视图加DBLINK实现数据的同步_20170216
查看>>
Redis在京东到家的订单中的使用
查看>>
idea 注释模板设置
查看>>
单例模式singleton为什么要加volatile
查看>>
Oracle_spatial的空间操作符
查看>>