LeetCode 400. 第N個數字(C++、python)
阿新 • • 發佈:2018-12-16
在無限的整數序列 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的一部分。
C++
class Solution { public: int findNthDigit(int n) { int a=9; long long i=1; int start=1; while(i*a<n) { n-=i*a; i++; a*=10; start*=10; } int last=start+(n-1)/i; int index=(n-1)%i; string tmp=to_string(last); return tmp[index]-'0'; } };
python
class Solution: def findNthDigit(self, n): """ :type n: int :rtype: int """ i=1 start=1 a=9 while i*a<n: n-=i*a i+=1 a*=10 start*=10 last=start+(n-1)//i index=(n-1)%i tmp=str(last) return int(tmp[index])