Nth Digit
题目地址:
https://leetcode.com/problems/nth-digit/description/
题目:
link: https://discuss.leetcode.com/topic/59342/intuitive-solution-with-comments

代码:
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).
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.解题思路:
link: https://discuss.leetcode.com/topic/59342/intuitive-solution-with-comments

代码:
/* number of the digits at each "level" 1-9: 9 digits 10-99 : 90 * 2 = 180 digits 100-999 : 900 * 3 = 2700 digits 1000-9999 : 9000 * 4 = 36000 digits**/ public int findNthDigit(int n) { if(n < 1) return 0; if(n < 10) return n; int counter = 1; //stores the level number int base = 0; //stores the biggest number from previous level while(n > (9 * Math.pow(10,counter -1) * (counter))){ base += 9 * Math.pow(10,counter -1); n -= (9 * Math.pow(10,counter -1) * (counter)); counter++; } //target is the actual number that has nth digit int target = base + ((n + counter - 1) / counter); //to get the ceiling of n / counter int offset = n % counter; offset = (offset == 0) ? 0:counter - offset; for(int i = 0; i < offset; i++){ target = target / 10; } return target % 10; }

Comments
Post a Comment