/*****************************************************问题描述*************************************************
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input:3
Output:3
Example 2:
Input:11
Output:0
Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
找到第n个数字
/*****************************************************我的解答*************************************************
/**
* @param {number} n
* @return {number}
*/
var findNthDigit = function(n) {
var number = n; //备份总数n
var numCount = 0; //存储数值位数
var theNumber = 0; //最后定位到的那个数
//先大概算出是几位数,1位数有9个数字,2位数有180个数字,依次类推
var bits = [1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000];
for(var bit = 1; bit < 11; bit++)
{
n -= bit * bits[bit - 1] * 9;
if(n <= 0)
{
numCount = bit;
break;
}
}
console.log('位数:' + numCount);
//然后算出是几位数的第几个数
n = number;
for(var i = 1; i < numCount; i++)
{
n -= i * bits[i - 1] * 9;
}
console.log('还剩多少:' + n);
var remain = n;
for(var j = 1; j <= numCount * bits[numCount - 1] * 9; j++)
{
n -= numCount;
if(n <= 0)
{
n += numCount;
break;
}
}
console.log('第几个数:' + j);
theNumber = bits[numCount - 1] + j - 1;
console.log('这个数是:' + theNumber);
//最后看是第几个数的第几位
var lastIndex = remain - (j - 1) * numCount;
console.log('第几位:' + lastIndex);
return theNumber.toString().split('')[lastIndex - 1];
};
findNthDigit(186);
console.log('the digit is:' + findNthDigit(11));
leetCode刷题记录51_400_Nth Digit
最新推荐文章于 2022-08-03 10:45:26 发布