C++_Accpeted


  • 0
       /* My code is not so clean... I will update it ASAP.
     counts the digitals:
    
     1 * 9
     2 * 10 * 9
     3 * 10 * 10 * 9
     4 * 10 * 10 * 10 * 9
     ``````
        */ 
    class Solution {
    public:
    int findNthDigit(int n) {
        if(n <= 9) return n;
        int digits = 0;
        int tmp = n;
        
        int base = 1;
        int i = 0;
        while(true){
            if(tmp - base * 9 * pow(10,i) < 0){break;}
            else{
                tmp = tmp - base * 9 * pow(10,i);
                i++;
                base++;
            }
        }
        
        i++;
        int j = tmp/i;
        int k = tmp%i;
        int begin = pow(10,i-1);
        begin = begin + j;
        
        int res = 0;
        if( k == 0) return (begin - 1) % 10;
        int digit = digitss(begin);
        tmp = begin;
        while( k > 0){
            int tmp2 = pow(10,digit - 1);
            res = tmp / tmp2;
            tmp = tmp - tmp2 * res;
            k--;
            digit--;
        }
        return res;
    }
    
    int digitss(int n){
        int digits = 0;
        while(n > 0){
        n = n/10;
        digits++;
        }
        return digits;
    }  };

Log in to reply
 

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