题解 | #数字序列中某一位的数字#
数字序列中某一位的数字
https://www.nowcoder.com/practice/29311ff7404d44e0b07077f4201418f5
#include <string> class Solution { public: int findNthDigit(int n) { if (n < 10) return n; int start = 1; int end = 10; long long bit = 1; // 小于10的数字一位数,1~9,共9个数字,9位; // 小于100的数字两位数,10~99,共90个数字,180位; // 小于1000的数字三位数,100~999,共900个数字,2700位; // 定位区间 while ((long long) n >= (end - start)*bit) { // 减之前位数 n -= (end - start) * bit; // 更新区间头尾 start *= 10; end *= 10; bit++; } // 0123456789 10 11 12 13 14 15 // (n-1) / bit 是定位到第几个数,bit是这个范围内的整数长度 // (n-1) % bit 是定位到这个整数上的在长度上的第几个 string res = to_string(start + (n-1)/bit); return res[(n - 1) % bit] - '0'; } };
2023-剑指-搜索算法 文章被收录于专栏
2023-剑指-搜索算法