原题链接在这里:https://leetcode.com/problems/nth-digit/#/description
题目:
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.
题解:
先找到是在几位数的范围,再找具体是哪个数,再找是这个数的哪一位.
Note: count 是long, 如果是int的话, n = Integer.MAX_VALUE会overflow.
Time Complexity: O(m), m是最后len*count的位数. Space: O(1).
AC Java:
1 public class Solution { 2 public int findNthDigit(int n) { 3 int len = 1; 4 long count = 9; 5 int start = 1; 6 7 //找到是几位数的范围 8 while(n > len*count){ 9 n -= len*count; 10 len += 1; 11 count *= 10; 12 start *= 10; 13 } 14 15 //找到具体的数 16 start += (n-1)/len; 17 18 //找到是这个数的第几位 19 String s = Integer.toString(start); 20 return s.charAt((n-1)%len) - '0'; 21 } 22 }