C++ straight-forward solution with explanation


  • 0
    L
    class Solution {
    public:
        int findNthDigit(int n) {
            int i = 0;
            while(n>0){
                i++;
                int minus = i*(pow(10,i)-pow(10,i-1));
                if(n-minus>0) n-=minus;
                else break;
            }
            int res = (n+i-1)/i+pow(10,i-1)-1;
            string result = to_string(res);
            return result[(n+i-1)%i]-'0';
        }
    };
    
    • we divided numbers into several parts:
      1~9 10~99 100~999 ...
    • first, we determine which part the result belongs to.
      the i in the while loop means the ith part.
    • then we find the number that the digit belongs to,
      which is res in the code.
    • finally we find the position of the digit in the number.

Log in to reply
 

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