400. Nth Digit

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
Find the n-th 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 < 2^31).
这里写图片描述
找出一系列数字按顺序排列之后的的第n位的值。

2,题目思路
不同位数有着不同的长度情况,因此,整个问题可以分成三个步骤来做。
1,找出给定位数的数字,其数字位数是多少(0-9?10-99?100-999?… )
2,利用位数情况,确定该数字。
3,利用偏移量,确定对应位数。

3,程序源码

class Solution {
public:
    int findNthDigit(int n) {
        int len = 1;//记录当前数字是几位数
        long count = 9;
        long starter = 1;//记录开始位置
        while(n - len*count>0){
            n = n -len*count;
            len++;
            count = count*10;
            starter = starter*10;
        }
        string res = to_string(starter + (n-1)/len);//因为starter中已经占有了len位长度了,因此n-1
        return res[(n-1)%len] - '0';
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值