Nth Digit LeetCode Solution

Last updated on July 21st, 2024 at 04:23 am

Here, We see Nth Digit LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Math

Companies

Google

Level of Question

Medium

Nth Digit LeetCode Solution

Nth Digit LeetCode Solution

Problem Statement

Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …].

Example 1:
Input: n = 3
Output: 3

Example 2:
Input: n = 11
Output: 0
Explanation: 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.

1. Nth Digit Leetcode Solution C++

class Solution {
public:
    int findNthDigit(int n) {
        int a = 9, d = 1;
        while (n - (long)a * d > 0)
        {
            n -= a * d;
            a *= 10;
            d += 1;
        }
        int num = pow(10, d - 1) + (n - 1) / d;
        cout<<num;
        return to_string(num)[(n - 1) % d] - '0';
    }
};

2. Nth Digit Leetcode Solution Java

class Solution {
    public int findNthDigit(int n) {
        int digit = 1;
        int num_digits_in_interval = 9;
        while (n - num_digits_in_interval > 0) {
            n -= num_digits_in_interval; 
            digit += 1;
            num_digits_in_interval = 9 * ((int) Math.pow(10, digit - 1))*digit;
            if (num_digits_in_interval < 0) break;
        }
        int base = ((int) Math.pow(10, digit - 1));
        int number =  base + (n - 1) / digit;
        char digit_in_number = String.valueOf(number).charAt((n - 1) % digit);
        return digit_in_number - '0';
    }
}

3. Nth Digit Solution JavaScript

var findNthDigit = function(n) {
    var len = 1;
    var range = 9;
    var base = 1;
    while(n>len*range)
    {
        n -= len *range;
        range *= 10;
        base *= 10;
        len++;
    }
    var num = base + Math.floor((n-1)/len);
    var s = num.toString();
    return parseInt(s[(n-1)%len]);
};

4. Nth Digit Solution Python

class Solution(object):
    def findNthDigit(self, n):
        if n <= 9:
            return n
        base = 9
        digits = 1
        while n > base * digits:
            n -= base * digits
            base *= 10
            digits += 1
        num = 10 ** (digits - 1) + (n - 1) // digits
        idx = (n - 1) % digits
        return int(str(num)[idx])
Scroll to Top