剑指 Offer 44. 数字序列中某一位的数字

剑指 Offer 44. 数字序列中某一位的数字

数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。

请写一个函数,求任意第n位对应的数字。

思路

首先确定这个位所在数字的位数,然后在确定在这个数字的第几位

因为下标从0开始,所以最开始的 0 是可以省略的。

1位数字有 9 个 长 1 * 9
2位数字有 90 个 长 2 * 90
3位数字有 900 个 长 3 * 900

  1. 确定数字位数
  2. 确定数字
  3. 确定在第几位

代码

class Solution {
public:
    int findNthDigit(int n) {
        int digit = 1;
        long long start = 1;
        long long count = 9;
        while (n > count) {
            n -= count;
            digit += 1;
            start *= 10;
            count = digit * start * 9;
        }
        // 这儿是 n-1 !!!!
        int num = start + (n - 1) / digit;
        count = (n-1) % digit; // 索引从0开始
        string s = to_string(num);
        int ans = s[count] - '0';
        return ans;

    }
};
posted @ 2022-04-28 15:39  沐灵_hh  阅读(20)  评论(0编辑  收藏  举报