|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | + |
| 6 | +namespace Math.Lib |
| 7 | +{ |
| 8 | + // Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... |
| 9 | + |
| 10 | + //Note: |
| 11 | + //n is positive and will fit within the range of a 32-bit signed integer (n < 231). |
| 12 | + |
| 13 | + //Example 1: |
| 14 | + |
| 15 | + //Input: |
| 16 | + //3 |
| 17 | + |
| 18 | + //Output: |
| 19 | + //3 |
| 20 | + //Example 2: |
| 21 | + |
| 22 | + //Input: |
| 23 | + //11 |
| 24 | + |
| 25 | + //Output: |
| 26 | + //0 |
| 27 | + |
| 28 | + //Explanation: |
| 29 | + //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. |
| 30 | + public class Nthdigit |
| 31 | + { |
| 32 | + //for this issue, there are two different ways to decribe a number |
| 33 | + //1 element. this is our common way |
| 34 | + //2 Nth digit. this is a new way |
| 35 | + public int FindNthDigit(int n) |
| 36 | + { |
| 37 | + long bas = 9; |
| 38 | + int digits = 1, i = 0; |
| 39 | + //first: getting n which digit is in |
| 40 | + while (n > bas * digits) // prevent overflowing. Since bas is long, so result of bas*digits is auto imporved as long |
| 41 | + { |
| 42 | + n -= (int)(bas * (digits++)); //nth |
| 43 | + i += (int)bas; //number of pasted elements |
| 44 | + bas *= 10; //1 digit->9; 2 digits->90; 3 digits->900, ... |
| 45 | + } |
| 46 | + //second: Nth digit ->element |
| 47 | + //in all numbers containing digits, pasted numbers |
| 48 | + int pasted = (int)((n - 1) / digits); |
| 49 | + int element = pasted + i + 1; |
| 50 | + //third: once getting the element Nth digits stands, |
| 51 | + //(n-1)%digits of element is solution |
| 52 | + int nth = (n - 1) % digits; |
| 53 | + return element.ToString()[nth] - '0'; |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments