数字序列中某一位的数字(C++)

数字序列中某一位的数字

题目

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

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

思路

需要根据每一位数字的位数来计算,一位数字有0-9共10个,两位数10到99共90个…
假设需要找的是第999位,先确定不在99之前(999>10+902),999-10-902 = 809,99之后的第809位肯定在999之前,因为100-999共有900位(900>809),809 = 269*3+2,所以第999位应该是269的第二位数字6

代码实现

class Solution {
public:
    int findNthDigit(int n) {
        if(n < 0)
            return -1;
        int digit = 1;
        while(true)
        {
            long long number =  countOfdigit(digit);
            if(n < number * digit)
                return findNthDigit(n, digit);
            n -= number * digit; 
            digit++;
        }
        return -1; 
    }
    int countOfdigit(int digit)
    {
        if(digit == 1)
            return 10;
        int count = (int)pow(10, digit - 1);
        return 9 * count;  // digit位数表示的数字所占的总位数
    }
    int findNthDigit(int n, int digit)
    {
        int number = begin_digit(digit) + n / digit;
        int num_shift = digit - n % digit; // 结果就是number的第(n % digit)位,要取出该数字,需要先将其移到最后一位,然后对高一位取余
        for(int i = 1; i < num_shift; i++)
            number /= 10;
        return number % 10;
    }
    int begin_digit(int digit)
    {
        if(digit == 1)
            return 0;
        return (int)pow(10, digit - 1);
    }
};
发布了63 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Jerry_Leo_liu/article/details/105135760
今日推荐