AcWing 57. 数字序列中某一位的数字

题目描述

数字以0123456789101112131415…的格式序列化到一个字符序列中。

在这个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。

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

样例

输入:13

输出:1

问题分析 

用变量 i 表示是几位数,s 表示 i位数有多少个,base表示 i位数的起始数。while循环退出后,i,s,base表示答案所在位置的情况。number表示答案在这个数中,wei表示答案在number中的位置(从0开始)。最后计算出ans返回。

代码实现

class Solution {
public:
    int digitAtIndex(int n) {
        long i = 1, s = 9, base = 1;
        while(n > s * i){
            n -= s * i;
            i++;
            s *= 10;
            base *= 10;
        }
        int number = base + (n - 1) / i;
        int wei = (n - 1) % i;
        int ans = 0;
        for(int j = 0; j < i - wei; j++){
            ans = number % 10;
            number /= 10;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/mengyujia1234/article/details/89892698
今日推荐