Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input: 3 Output: 3
Example 2:
Input: 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
這道題還是蠻有創意的一道題,是說自然數序列看成一個長字符串,問我們第N位上的數字是什么。那么這道題的關鍵就是要找出第N位所在的數字,然后可以把數字轉為字符串,這樣直接可以訪問任何一位。那么我們首先來分析自然數序列和其位數的關系,前九個數都是1位的,然后10到99總共90個數字都是兩位的,100到999這900個數都是三位的,那么這就很有規律了,我們可以定義個變量cnt,初始化為9,然后每次循環擴大10倍,再用一個變量len記錄當前循環區間數字的位數,另外再需要一個變量start用來記錄當前循環區間的第一個數字,我們n每次循環都減去len*cnt (區間總位數),當n落到某一個確定的區間里了,那么(n-1)/len就是目標數字在該區間里的坐標,加上start就是得到了目標數字,然后我們將目標數字start轉為字符串,(n-1)%len就是所要求的目標位,最后別忘了考慮int溢出問題,我們干脆把所有變量都申請為長整型的好了,參見代碼如下:
class Solution { public: int findNthDigit(int n) { long long len = 1, cnt = 9, start = 1; while (n > len * cnt) { n -= len * cnt; ++len; cnt *= 10; start *= 10; } start += (n - 1) / len; string t = to_string(start); return t[(n - 1) % len] - '0'; } };
參考資料:
https://discuss.leetcode.com/topic/59314/java-solution