zoukankan      html  css  js  c++  java
  • LeetCode--400--第N个数字

    问题描述:

    在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 个数字。

    注意:
    是正数且在32为整形范围内 ( n < 231)。

    示例 1:

    输入:
    3
    
    输出:
    3
    

    示例 2:

    输入:
    11
    
    输出:
    0
    
    说明:
    第11个数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是0,它是10的一部分。
    

    方法(times out):

     1 class Solution(object):
     2     def findNthDigit(self, n):
     3         """
     4         :type n: int
     5         :rtype: int
     6         """
     7         if n < 10:
     8             return n
     9         lis = [0,1,2,3,4,5,6,7,8,9]
    10         
    11         for i in range(10,n+1):
    12             templist = []
    13             while i != 0:
    14                 temp = i % 10
    15                 i = i // 10
    16                 templist.append(temp)
    17             templist.reverse()
    18             for i in templist:
    19                 lis.append(i)
    20         return lis[n]

    官方:

      1-9         9 * 1 = 9个

      10-99     90 * 2 = 180个

      100-999  900 * 3 = 270个

          设 digit代表几位数1,2,3,base代表每位数的个数9,90,900,ith代表该数的起始位置10,100,1000

    设 n = 12

    首先判断12在

     1 class Solution(object):
     2     def findNthDigit(self, n):
     3         """
     4         :type n: int
     5         :rtype: int
     6         """
     7         digit = 1
     8         base = 9
     9         ith = 1
    10         while n > digit * base:
    11             n -= digit * base
    12             ith += base
    13             digit += 1
    14             base = 10*base
    15         return ord(str((n-1)//digit + ith)[(n-1)%digit]) - ord('0')
  • 相关阅读:
    Java异常
    JS多个对象添加到一个对象中
    JSON.parse(),JSON.stringify(),jQuery.parseJSON()
    java中什么是序列化和反序列化
    html颜色字体字符代码
    冒泡排序应用
    HTML 速查列表
    html初学(一)
    html初学(二)
    一次、二次、三次指数平滑计算思想及代码
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9721933.html
Copyright © 2011-2022 走看看