Clear explanation for Nth Digit


  • 0
    S

    the regularity

    --- 1 - 9 : 9
    --- 10 - 99 : 90 * 2
    --- 100 - 999 : 900 * 3
    --- 1000 - 9999 : 9000 * 4

    k the kth layer, starting from 1
    on kth layer, each number consists of k digits
    note: n-1
    (n-1) / k == the position in the layer array index

    public class NthDigit {
        public int findNthDigit(int n) {
         	long m = n;
            int k = 1;
            long countDigits = 9;
    
            while (m > countDigits) {
            	m -= countDigits;
            	k++;
            	countDigits = 9 * (long)Math.pow(10, k - 1) * k;
            }
            long number = (long)Math.pow(10, k - 1) + (m - 1) / k;
    
            return String.valueOf(number).charAt((int)(m - 1) % k) - '0';
        }
    }
    

  • 0
    S

    @SpicyZinc said in Clear explanation for Nth Digit:

    the regularity
    --- 1 - 9 : 9
    --- 10 - 99 : 90 * 2
    --- 100 - 999 : 900 * 3
    --- 1000 - 9999 : 9000 * 4
    k the kth layer, starting from 1
    on kth layer, each number consists of k digits
    note: n-1
    (n-1) / k == the position in the layer array indexr

    explained very clear, good solution


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.