400. Nth Digit

142 篇文章 0 订阅
问题描述

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 < 231).

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.

题目链接:


思路分析

找到一连串的1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …的第n个数字。

真的是easy题么,好难啊。完全不会的。
首先确定这是一个几位数,有9个一位数,90个两位数,900个三位数……所以用n循环减去9,2*90,3*900……就可以得到它是几位数。

然后用这时的(n-1)%digits + 1得到这个第n个数字是这个数的第几位。

再确定这个数是多少,首先先制造一个digits位数,然后再加上n/digits或者n/digits - 1(当这个数字是数的最后一位的时候,要往前回一个数。否则算出来的是下一个数了。)

最后再辗转处10将这个数字降到最后一位,模10返回。

代码
class Solution {
public:
    int findNthDigit(int n) {
        //find the number of the digits
        long digits = 1, base = 9;
        while (n - digits*base > 0){
            n = n - digits*base;
            digits++;
            base *= 10;
        }
        //find the index of the nth in the num
        int index = (n - 1) % digits + 1;
        //find the num
        long num = 1;
        for (int i = 1; i < digits; i++){
            num *= 10;
        }
        if (index == digits)
            num += n/digits - 1;
        else
            num += n/digits;
        //return the nth
        for (int i = index; i < digits; i++){
            num /= 10;
        }
        return num % 10;

    }
};

时间复杂度:
空间复杂度: O(1)


反思

太难了……数学题啊……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值