400. 第 N 位数字

107 阅读1分钟

image.png

  • 先找到目标数字
    • 先找到x位数的起始数字,如154的起始数字为100。规律:所有x位数位数总和为 x*9*10^(x-1)
  • 再找到数字内偏移量,即可定位
class Solution {
    public int findNthDigit(int n) {
       int digits = 1; // 表示目标数字有多少位
       int count = 1;
        while (n > (long) digits * 9 * count) {
            n -= digits * 9 * count;//位数不断减去
            count *= 10;
            digits++;
        }

        int start = (int) Math.pow(10, digits - 1);// 起始数字
        int number = start + (n - 1) / digits;// 目标数字 n > 0 , n - 1
        int offset = (n - 1) % digits; // n - 1 // 数字内偏移量
        String str = String.valueOf(number);
        return str.charAt(offset) - '0';
    }
}