Swift solution, 15 ms (now beating 100%) with explanation


  • 0
    S

    Solution based on looking for the number which includes the n-th digit by finding the interval of that number (like 1...9, 10...100, 100...1000, etc.) and then find the actual number in that interval and the index of the digit.

    class Solution {
        func findNthDigit(_ n: Int) -> Int {
            if n <= 0 { return 0 }
            
            // Find the interval in which the digit will be
            var digitMultiplier = 1 // number of digits of numbers in current interval
            var fromLimit = 1 // start of the interval
            var toLimit = 10 // end of the interval
            var passedDigitCount = 0 // count of digits of all numbers in passed intervals
            var nextLimitPassedDigitCount = 9 // number of passed digits if we move to the next interval
            
            while n > nextLimitPassedDigitCount {
                passedDigitCount = nextLimitPassedDigitCount
                fromLimit = toLimit
                toLimit *= 10
                digitMultiplier += 1
                nextLimitPassedDigitCount += (toLimit - fromLimit) * digitMultiplier
            }
            
            // we know that the number of which's digit we are looking for is somewhere in (fromLimit..<toLimit) and that there are only "digitMultiplier"-digit numbers
            // just find the number and the index of the digit
            let n = n - passedDigitCount
            var number = fromLimit + (n - 1) / digitMultiplier
            let digitIndex = ((n - 1) % digitMultiplier) + 1
            
            // get digit at "digitIndex" index from right
            number /= Int(pow(10, Double(digitMultiplier - digitIndex)))
            return number % 10
        }
    }
    

Log in to reply
 

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