share my cpp solution with comments


  • 0
    int findNthDigit(int n) 
    {
        long base = 9;
        long len = 1;
        long start = 1;
        
        // find length
        while (n > base * len)
        {
            n -= base * len;
            len++;
            start *= 10;
            base *= 10;
        }
        
        // find number
        int num = start + (n - 1) / len;
        
        // find index
        int index = (n - 1) % len;
        
        // fetch 
        char buf[32] = {0};
        sprintf(buf, "%u", num);
        return buf[index] - '0';
    }

Log in to reply
 

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