数字序列中某一位的数字
1.题目描述
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
示例 2:
限制:
0 <= n < 2^31
2.思路
1.确定第n位是几位数:
每个位数对应有9*pow(10,digits-1)*digits个数。
2.确定是该位数的第几位:
pow(10,digits-1) + n/digits;
3.位数取余得到是数字上的第几位。
3.代码
class Solution {
public:
int findNthDigit(int n) {
if(n < 10){
return n;
}
int digits = 1;//代表数字的位数
while(n > 9*pow(10,digits-1)*digits){
n -= 9*pow(10,digits-1)*digits;
digits++;
}
//得到n是代表的数字对应的第几个数
int res = pow(10,digits-1) + n/digits;
int mod = n % digits;
if(mod == 0){
return (res- 1) % 10;
}
else{
return res/(int)pow(10,digits-mod)%10;
}
}
};