Java Accepted Solustion


  • 0
    Z

    Need to be careful with int overflow.

    public class Solution {
        public int findNthDigit(int n) {
            int digits = 1;
            long total = 0;
            long power = 1;
            while (true) {
                total += 9 * digits * power;
                if (total >= n) break;
                digits++;
                power *= 10;
            }
            total -= 9 * digits * power;
            long num = power + (n - total - 1) / digits;
            String s = "" + num;
            return s.charAt((int)((n - total - 1) % digits)) - '0';
        }
    }
    

Log in to reply
 

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