java solution with explanation


  • 0
    M
    1-9,    the total number is 1*9*1;
    10-99,  the total number is 2*9*10;
    100-999,the total number is 3*9*100;
    

    for n digit number ,the total number is n*9*pow(10,n-1),
    so the tips as follow:

    • find the result in x digit number;
    • find the very x digit number, the ith of x digit number;
    • find the final result, the rest th digit of the very x digit number;
    public class Solution {
        public int findNthDigit(int n) {
            int n0=1;
            int index=1;
            int count=index*9*n0;
            while(n>count){
                n-=count;
                index++;
                n0*=10;
                count=index*9*n0;
                if(count<0)break;
            }
            int rest=(n-1)%index;
            int ith=(n-1)/index;
            int ret=n0+ith; //the final result is the rest th digit of the ith index digit number 
            char[] chArray=(""+ret).toCharArray();
            return chArray[rest]-'0';
        }
    }
    

Log in to reply
 

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