Problem Statement
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).
Link to gitHub :Code
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Link to gitHub :Code
Example
Example 1 Input: Output: 3 3 Example 2 Input: Output: 11 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.
Solution
- Find the length of the number of the nth digit
- Find the actual number at the nth digit
- Find the nth digit and return
public static int Get(int n) { int len=1; long count =9; int start=1; while(n>len*count) { n-=len*count; len+=1; count*=10; start*=10; } start+=(n-1)/len; //Convert to string String s=Integer.toString(start); //return the numeric value return Character.getNumericValue(s.charAt((n-1)% len)); }
No comments:
Post a Comment