[leetcode] 400. Nth Digit 解題報告
阿新 • • 發佈:2019-02-05
題目連結:https://leetcode.com/problems/nth-digit/
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.
思路:可以分三步來做:
1.找出給定的n落在幾位數的範圍內
2.找到具體落在哪個數字
3.找出具體在哪一位上
分析可以得出一位有9個數字,二位數有90個數字,三位數有900個數,依次類推.因此可以每次增加一位數字,看n是否還在這個範圍內.例如給定n = 150,首先一位有9個數字,所以位數可以+1,這樣n-9 = 141. 然後2位的數字有2*90= 180,大於141,所以目標數字肯定是2位的.然後求具體落在哪個數字.可以用10+(141-1)/2 = 80求出.再求具體落在哪一位上,可以用(141-1)%2=0求出為第0位,即8.如此即可.
程式碼如下:
參考:https://discuss.leetcode.com/topic/59314/java-solution/4class Solution { public: int findNthDigit(int n) { long digit = 1, ith = 1, base = 9; while(n > base*digit) { n -= base*(digit++); ith += base; base *= 10; } return to_string(ith+(n-1)/digit)[(n-1)%digit]-'0'; } };