數字以0123456789101112131415…
的格式序列化到一個字符序列中。在這個序列中,第5位(從下標0開始計數)是5,第13位是1,第19位是4,等等。
請寫一個函數,求任意第n位對應的數字。
示例 1:
輸入:n = 3
輸出:3
示例 2:
輸入:n = 11
輸出:0
限制:
0 <= n < 2^31
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析:
找規律
解答:
class Solution {
public:
int findNthDigit(int n) {
if(n<10) return n;
int base = 1;
while(n>9*pow(10,base-1)*base){
n-=9*pow(10,base-1)*base;
base++;
}
int res = pow(10,base-1) + n/base;
int mod = n%base;
if(mod==0){
return (res-1)%10;
}
else{
return res/(int)pow(10,base-mod)%10;
}
}
};