LeetCode/第N位数字(找规律)

给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出并返回第 n 位上的数字

1. 找规律模拟

class Solution {
public:
    int findNthDigit(int n) {
        long d = 1, count = 9;
        while (n >  d * count) {
            n -= d * count;//削减后移量
            d++;
            count *= 10;
        }
        //出循环的n表示排在当前位的第n个,不可能为0
        int index = n - 1;//注意!!要用于初始值第0个数
        int start = (int) pow(10, d - 1);//当前位初始值
        int num = start + index / d;//得到对应数
        int digitIndex = index % d;//得到在数中的位置
        int digit = (num / (int) (pow(10, d - digitIndex - 1))) % 10;
        return digit;
    }
};

2. 极简写法

class Solution {
public:
    int findNthDigit(int n) {
        long num = n;
        int len = 1;
        long base = 10;
        while (len * base < num) {
            num += base;
            base *= 10;
            len++;
        }
        return to_string(num / len)[num % len] - '0';
    }
};
posted @ 2022-07-30 20:53  失控D大白兔  阅读(31)  评论(0编辑  收藏  举报