数字序列中某一位的数字

class Solution {
public:
    int digitAtIndex(int n) {
        if(!n)  return 0;
        long long start=1,len=1,cnt=1;//记录区间的起始位置,记录区间长度,cnt记录当前是几位数
        //往后走,跨度为一个区间
        while(1)
        {
            len=start*9*cnt;
            if(n<len)   break;
            n-=len;
            start*=10;
            cnt++;
        }
        //从当前区间开头往后走,跨度为一个数字
        start+=(n+cnt-1)/cnt-1;//上取整再-1
        //也可以通过下面的循环实现
        // while(n>cnt)
        // {
        //     n-=cnt;
        //     start++;
        // }
        int offset=n%cnt?n%cnt:cnt;//offset记录数字里的第几位数,n%cnt==0需要特判
        //求start的第offset位数
        for (int i = 0; i < cnt-offset; i ++ )  start/=10;//右移
        return start%10;
    }
        
};
posted @ 2023-04-21 14:57  穿过雾的阴霾  阅读(15)  评论(0)    收藏  举报