letecode [400] - Nth Digit

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,...,9,10,11,计算第n个数字指向的值。如n=9指向9,n=11指向0.

理  解:

  开始觉得这个题目很难,大致看了其他人的做法,尝试自己去想通这个过程,发现还是比较容易的。

  n<10时,返回n。

  计算n对应的十进制序列的位数length,再计算它超过该十进制初始值多少位lastN,计算它指向的十进制数,再取得执向的具体某位的值。

代 码 C++:

class Solution {
public:
    int findNthDigit(int n) {
        if (n < 10)
            return n;
        int length = 0, lastN, base, index;
        while (n > 0) {            // 计算n对应的10进制区间,即位数
            lastN = n;
            n = n - 9 *(length+1)*pow(10, length);
            length++;
        }
        base = lastN / length + pow(10, length - 1);     // 计算n指向的十进制数
        index = lastN % length;        // 计算n指向十进制数的第几位
        if(index==0){
            base = base - 1;
            index = length;
        }
        base = base / pow(10, length - index);
        base = base % 10;        // 获取指向的数字。
        return base;
    }
};

运行结果:

  执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
  内存消耗 :8.5 MB, 在所有 C++ 提交中击败了68.64%的用户

转载于:https://www.cnblogs.com/lpomeloz/p/11055291.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值