-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path400_NthDigit.swift
38 lines (35 loc) · 938 Bytes
/
400_NthDigit.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
// 400_NthDigit.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-11-26.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:400 Nth Digit
URL: https://leetcode.com/problems/nth-digit/
Space: O(lgN)
Time: O(1)
*/
class NthDigit_Solution {
func findNthDigit(_ n: Int) -> Int {
// Firstly, find the len for that nth number.
var len = 1
var count = 9
var remainedN = n
var start = 1
while remainedN > len * count {
remainedN -= len * count
len = len + 1
count = count * 10
start = start * 10
}
// Secondly, find the number the Nth digit belongs to.
start += (remainedN - 1) / len
let startString = String(start)
// Thirdly, find the character the Nth digit of that finded number.
let indexedCharacter = [Character](startString.characters)[(remainedN - 1) % len]
return Int(String(indexedCharacter))!
}
}