题解 | #数字序列中某一位的数字# 简单、直观、易理解
数字序列中某一位的数字
https://www.nowcoder.com/practice/29311ff7404d44e0b07077f4201418f5
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
int findNthDigit(long long n) {
if (n < 10) {
return n;
}
// 按照十进制占的bit数量依次梳理各个区间:[0, 10) [10, 100) [100, 1000), [1000, 10000)....
long long min = 0;
long long max = 10;
long long count = max - min; // 转成string后[min, max)区间内总bit数
long long bits = 1; // 对应 [min, max) 区间的每个数组转成string后占的bit数
while (n >= count) {
n -= count;
++bits;
min = max;
max = min * 10;
count = (max - min) * bits;
}
// 计算目标对应当前区间第几个数字,以及返回这个数字的第几位
long long th = n / bits;
long long bit_th = n % bits;
long long target = min + th;
std::string tmp(std::to_string(target));
return tmp.at(bit_th) - '0';
}
};
code中有些变量是非必须的,但是为了方便理解,这里保留了一些冗余的变量
