c++


  • 0
    /*
    * Keep subtracting the total number of digits as we go from 1..9,10..99,100..999,..and so on.
    * when it will become negative break and subtract the total whole numbers possible for the digits
    *then increment if needed,
    *start diving from the back of the number to extract the digits.
    *return the digit
    */
    class Solution {
    public:
        int findNthDigit(int n) {
            long long count = 9,digits=1,number=0,temp_n=n;
            while(temp_n)
            {
                if(temp_n <= (count*digits))
                    break;
                else
                    temp_n = temp_n - (count*digits);
                
                number += count;    
                count *= 10;
                digits++;
            }
            
            number += (temp_n)/digits;
            
            if(temp_n%digits)
            {
                number++;
                temp_n = temp_n%digits;
            }
            else
                temp_n = digits;
            
            for(int i=0;i<(digits - temp_n);i++)
            {
                number = number/10;
            }
            
            return number%10;
        }
    };
    

Log in to reply
 

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