数字序列中某一位的数字
数字以0123456789101112131415…的格式序列化到一个字符序列中。
在这个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数求任意位对应的数字。
样例
输入:13
输出:1、
数学
时间复杂度O(n)
class Solution {
public int digitAtIndex(int n) {
int i = 1;//几位数
long s = 9;//s表示位数共有多少个,一定要用Long,防止溢出
long base = 1;//base表示位数的起始值
long number;//表示是几位数中的第几位数
while(n > i * s){
n-=i * s;//n-9-2*90-3*900
i++;
s *= 10;
base *= 10;
}
if(n % i == 0){
number = base + n / i - 1;
return (int)number % 10;
}else{
number = base + n / i;//有余数,说明是第多少位数中的第n%i位数
int m = n % i;
for(int j = 0;j < i - m;j++){
number = number / 10;
}
return (int)number % 10;
}
}
}