剑指 Offer 44. 数字序列中某一位的数字

tech2022-11-26  100

剑指 Offer 44. 数字序列中某一位的数字

题目描述代码实现

题目描述

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

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

示例 1:

输入:n = 3 输出:3

示例 2:

输入:n = 11 输出:0

限制:

0 <= n < 2^31

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof

代码实现

class Solution { public: int findNthDigit(int n) { int n_digits = 1; long digit_count = 0; while(true) { digit_count += 9 * pow(10, n_digits - 1) * n_digits; if(digit_count >= n) break; n_digits++; } int pre_digit_count = digit_count - 9 * pow(10, n_digits - 1) * n_digits; int nth_number = (n - pre_digit_count - 1) / n_digits; int nth_digits = (n - pre_digit_count - 1) % n_digits; int tar_number = pow(10, n_digits - 1) + nth_number; int result = tar_number / pow(10, n_digits - nth_digits - 1); result = result % 10; return result; } };
最新回复(0)