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

题目链接:剑指 Offer 44. 数字序列中某一位的数字

方法:找规律

解题思路

  1. 找第\(n\)位对应的数为几位数;
  2. 找该数的具体值;
  3. 找第\(n\)位在该数中的第几位。

力扣

代码

class Solution {
public:
    int findNthDigit(int n) {
        int digit = 1; 
        long long start = 1, count = 9;
        while (count < n) { // 1
            n -= count;
            start *= 10;
            digit ++ ;
            count = 9 * start * digit;
        }
        int num = start + (n - 1) / digit; // 2
        string s = to_string(num);
        return s[(n - 1) % digit] - '0'; // 3
    }
};

复杂度分析

时间复杂度:\(O(logn)\)
空间复杂度:\(O(1)\)

参考

面试题44. 数字序列中某一位的数字(迭代 + 求整 / 求余,清晰图解)

posted @ 2023-04-08 23:57  lixycc  阅读(19)  评论(0)    收藏  举报