<div class="image-package"><img src="https://img.haomeiwen.com/i1648392/32841d53d2556d21.jpg" img-data="{"format":"jpeg","size":177255,"height":900,"width":1600}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><blockquote><p>给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出并返回第 n 位数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
解释:第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是 0 ,它是 10 的一部分。
提示:
1 <= n <= 231 - 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/nth-digit
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。</p><p>
</p></blockquote><h1 id="exjun">题解</h1><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/00c8f738190f7a5a.jpg" img-data="{"format":"jpeg","size":25688,"height":272,"width":998}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><h2 id="6nrel">Swift</h2><p>直接计算</p><blockquote><p>import UIKit
class Solution {
func findNthDigit(_ n: Int) -> Int {
var n = n
// 整数位数
var d = 1
var count = 9
while n > d * count {
n -= d * count
d += 1
count *= 10
}
let index = n - 1
let start = Int(pow(Double(10), Double(d - 1)))
let num = start + index / d
let digitIndex = index % d
let digit = (num / Int(pow(Double(10), Double(d - digitIndex - 1)))) % 10
return digit
}
}
// print(Solution().findNthDigit(3))
print(Solution().findNthDigit(12))
</p></blockquote><p>
</p><p>
</p><p>
</p><p>
</p><p>
</p>
网友评论