Leetcode 面试题44. 数字序列中某一位的数字

问题描述

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

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

示例 1:

输入:n = 3
输出:3

解题报告

一位数的数字有 10 个,占了 10
二位数的数字有 90 个,占了 180
三位数的数字有 900 个,占了 2700
……
所以解题思路是:

  • 先确定几位数 digits
  • 然后确定从 digits 开头的第几个数
  • 最后确定具体数值的具体某位数字。

实现代码

class Solution {
public:
    int findNthDigit(int n) {
        if(n==0) return 0;
        n-=1;
        long base = 9,digits = 1;
        while (n - base * digits > 0){
            n -= base * digits;
            base *= 10;
            digits ++;
        }
        // n/digits 表示从digits开头的第几个数
        // n%digits 表示具体数值的具体第几位数字
        long number=pow(10, digits-1)+n/digits;
        return int(to_string(number)[n%digits]-'0');
    }
};

参考资料

[1] Leetcode 面试题44. 数字序列中某一位的数字

猜你喜欢

转载自blog.csdn.net/qq_27690765/article/details/106730859