leetcode 400. Nth Digit

本文介绍了一种高效算法来找到无限整数序列1,2,3,4,5,6,7,8,9,10,11,...中的第N位数字。通过分析数字序列的特点,算法首先确定目标数字所在的位数范围,然后精确到具体数字及位位置,最终返回所需数字。示例展示了当输入为3和11时,如何分别得到3和0作为输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:
如果n<9, 返回n
如果n<9 + 2 * 90, 说明是某个两位数中的一位
如果n<9 + 2 * 90 + 3 * 900,说明是某个三位数中的一位

首先判断第n个数是属于几位数,然后判断属于该数的第几位

注意 表达式的结果可能溢出,导致结果错误
原题目:

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 2E31).

Example 1:
Input:
3
Output:
3

Example 2:
Input:
11
Output:
0

Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.

AC解,C++代码,菜鸟一个,请大家多多指正

class Solution {
public:
    int tenPower(int n) {
        int ret = 1;
        while (n > 0) {
            ret *= 10;
            n--;
        }
        return ret;
    }
    int findNthDigit(int n) {
        int i = 0;
        while (true) {
            i++;
            if ((n - 1) / (i * 9) >= tenPower(i - 1)) {
                n -= i * 9 * tenPower(i - 1);
            }
            else {
                break;
            }
        }

        int num_pos = (n - 1) / i + tenPower(i - 1);
        int bit_pos = (n - 1) % i;

        return (num_pos / tenPower(i - 1 - bit_pos)) % 10;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值