Accepted 7-line concise C++ solution with explanation


  • 0
    D
    1. Locate the number of digits
    2. Locate the number
    3. Locate the digit within the number
    int findNthDigit(int n) {
            long digit = 1, base = 9;
            while (n - digit * base > 0) { // locate the number of digits
                n -= digit * base;
                digit++;
                base *= 10;
            }
            string s = to_string(base / 9 + (n - 1) / digit); // locate the number
            return s[(n - 1) % digit] - '0'; // locate the digit within the number
        }
    

Log in to reply
 

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