Java solution with comments


  • 1
    G
    // k: number of digits of an integer. E.g, k = 1 for 1,2,3,4,... k = 2 for 10, 11, 12...
    // so we have k-digits arrays like:
    // k = 1: 1, 2, 3, 4, 5
    // k = 2: 10, 11, 12, ...
    // base: start integer of a k-digits array. E.g base = 1 when k=1, base = 10 when k = 2...
    // The strategy is to find the k-digits array and then find out the corresponding integer 
    // and the digit inside the integer
    public class Solution {
        public int findNthDigit(int n) {
            int k = 1;
            long base = 1;
    
            // find the corresponding k-digits array
            while(n > base * 9 * k){
                n -= base * 9 * k;
                k++;
                base = base * 10;
            }
            
            // corresponding integer in the array
            long value = base + (n-1)/k;
            
            // digit of the integer
            return Long.toString(value).charAt((n-1)%k) - '0';
        }
    }
    

  • 0

    @gigimei elegant code, super like it, one slight modification for passing newly adding test case: for example when you pass the Integer.MAX_VALUE (2147483647), you will get error, cause base * 9 * k might overflow, and become negative, and does not quit the while loop when it should do.

    Quick fix would be while(n > (long)base9k)


  • 0
    J

    Not a fan of long.

    below is my solution

    public class Solution {
        public int findNthDigit(int n) {
            int idx = n - 1;
            int bit = 1;
            int base = 1;
            
            while(idx - 9 * base * bit >= 0 && bit < 9) {
                idx -= (9 * base * bit);
                base *= 10;
                bit ++;
            }
            
            int num = base + idx / bit;
            return String.valueOf(num).charAt(idx % bit) - '0';
        }
    }
    

  • 0
    N

    Hi @gigimei ,

    Could you please let me know why did you subtract "-1" in "n-1"?
    TIA


Log in to reply
 

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