Python code. interval → Number → Position


  • 0
    Y
    class Solution(object):
        def findNthDigit(self, n):
            """
            :type n: int
            :rtype: int
            """
            import math
            m = 0
            mn = n
            # find out the interval where the nth digit is
            while mn >= 9*10**(m-1)*m:
                mn = mn - 9*10**(m-1)*m
                x = 10**m - 1
                m = m + 1
                if mn <= 9*10**(m-1)*m:
                    break
                    
            # find out the number where the nth digit is
            nup = x + math.ceil(mn/m)
            ndn = x + math.floor(mn/m)
            
            # find out the digit
            if (nup - ndn) == 0:
                nth = int(str(nup)[m-1])
            else:
                p = int(mn % m)
                nth = int(str(nup)[p-1])
            return nth

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.