在無限的整數序列?1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第?n?個數字。
注意:
n?是正數且在32為整形范圍內?(?n?< 231)。
示例 1:
輸入: 3 輸出: 3
示例 2:
輸入: 11 輸出: 0 說明: 第11個數字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是0,它是10的一部分。
?
class Solution {
public:int findNthDigit(int n) {long long digit = 1; //當前一個數有幾位數long long start = 1; //當前從哪個數開始long long total = 9; //當前digit位數的數有多少個while(n > digit * total){n -= total * digit;digit += 1;start *= 10;total *= 10;}int number = start + (n - 1) / digit; //以輸入11為例子 2 / 2 == 1 但是第二位在10上,而不是在start + 2 / 2 == 11上,所以n - 1string str = to_string(number);int res = str[(n - 1) % digit] - '0';//下標從0開始所以n - 1return res;}
};
?