2021年01月08日 周五 天气晴 【不悲叹过去,不荒废现在,不惧怕未来】
1. 题目简介
2. 迭代 + 求整 / 求余
2.1 解题思路
以下解题思路来自大佬 Krahets,十分感谢。
2.2 代码
注意: 定位到所在的数字(num
),以及求取最终的结果时,因为start
是从0
号位置开始的,所以n 要减1。
class Solution {
public:
int findNthDigit(int n) {
int digit = 1;
long start = 1, count = 9;
while(n>count){
n -= count;
digit += 1;
start *= 10;
count = digit*start*9;
}
// 定位到所在的num,注意 n 要减1
long num = start + (n-1) / digit;
// 得到最终结果,注意 n 要减1
return to_string(num)[(n-1) % digit] - '0';
}
};
因为 count = digit*start*9; start *= 10;
,所以时间复杂度以及最后字符串的长度(num
转化而来)都是 log
级别的。
参考文献
《剑指offer 第二版》
https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/solution/mian-shi-ti-44-shu-zi-xu-lie-zhong-mou-yi-wei-de-6/