Header Ad

Leetcode Nth Digit problem solution

In this Leetcode Nth Digit problem solution you are given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].

Leetcode Nth Digit problem solution


Problem solution in Python.

def findNthDigit(self, n: int) -> int:
    if n < 10:
        return n
    i = 0
    count = 0
    num = 1
    while True:
        next = ((9 * (i + 1)) * num)
        i += 1
        if count + next >= n:
            break
        num *= 10
        count += next
    count += 1
    move, digit = divmod(n - count, i)
    count += move * i
    num += move

    return int(str(num)[digit])



Problem solution in Java.

class Solution {
    public int findNthDigit(int n) {
        long step = 1;
        long size = 9 * (int)Math.pow(10, step-1);
        while (n > step * size) {
            n -= step * size;
            step++;
            size = 9 * (int)Math.pow(10, step-1);
        }        
        long number = size/9 + (long)Math.ceil((n*1.0d)/step) -1;
        char ansDigit = String.valueOf(number).charAt((int)((n%step-1+step)%step));
        return (int)(ansDigit - '0');
    }
}


Problem solution in C++.

class Solution {
public:
    #define ll long long
    ll power(int a){
        a--;
        ll i=1;
        while(a){
            a--;
            i*=10;
        }
        return i;
    }
    int findNthDigit(int n) {
        if(n<10)
            return n;
        ll div=9;
        ll c=1;
        while((n-div)>0){ 
            n-=div;
            c++;
            div=9*power(c)*c;
        }
        n--;
        string tmp=to_string(power(c)+n/c);
        cout << tmp;
        return (tmp[n%c]-'0');
    }
};


Problem solution in C.

int findNthDigit(int n){
        long digits_passed = 9;
        long digits_count = 1;
        long current_count = 0;
        long running_number = 0;
        long prev = 0;
        long diff, add, remainder;
        if(n <= 9)
                return n;
        while((current_count+ digits_passed*digits_count) < n){
                current_count += digits_passed*digits_count;
                digits_count++;
                digits_passed *= 10;
                running_number += (digits_passed/10);
        }
        diff = (n - current_count);
        if(diff % digits_count == 0){
                running_number += (diff/digits_count);
                return running_number%10;
        }
        else
        {
                prev = diff;
                diff += (digits_count - diff % digits_count);
                running_number += (diff/digits_count);
                prev = (prev % digits_count);
                digits_count = digits_count - prev;
                while(digits_count--)
                        running_number /= 10;
                return running_number%10;
        }
        return -1;

}


Post a Comment

0 Comments