在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …中找到第 n 个数字。
注意:n 是正数且在 32 位整形范围内 ( n < 2^31)。
这里的第 n 个数字,其实指的是第 n 位数字。例如输入 11,那么应该输出 0(来自于数字 10)。
写出这些数据,可以发现:
9 * 10^k
个所以解决思路就是先通过循环,确定所要查找的数字落在第几位。最后通过计算找出数字即可。例如对于 n=13 来说,过程如下:
num = 10 + int(4/2) - 1 = 11
pos = 4 - 2 * (11 - 10) - 1 = 1
代码实现如下:
// ac地址:https://leetcode-cn.com/problems/nth-digit/
// 原文地址:https://xxoo521.com/2020-03-09-n-number/
/**
* @param {number} n
* @return {number}
*/
var findNthDigit = function(n) {
for (let bit = 1; bit < 32; ++bit) {
const startNum = Math.pow(10, bit - 1);
const bitSum = 9 * startNum * bit;
if (n > bitSum) {
n -= bitSum;
} else {
let num = startNum + Math.ceil(n / bit) - 1;
let pos = n - bit * (num - startNum) - 1;
return num.toString(10)[pos];
}
}
};
n 的取值范围决定了循环的次数,也决定了时间复杂度。