LeetCode刷题笔记--400. Nth Digit

400. Nth Digit

400. Nth Digit

Easy

228705FavoriteShare

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.

这道题需要先找规律,然后按照规律来算,特别需要注意当p正好等于0的时候比较特殊,需要特殊处理。等于0的情况我在vs里调过的。

class Solution {
public:
    int findNthDigit(int n) {
        //先找一下规律:
        //1位的情况,从1~9,总共9个数字
        //2位的情况,从10~99,总共90*2个数字
        //3位的情况,从100~999,总共900*3个数字
        //n位的情况,从10^(n-1)~10^(n)-1,总共有9*10^(n-1)*n个数字
        if(n<10)return n;
        int b=1;//用来记录在上述哪段范围内
        int ans=0;
        int ans1=0;
        long temp=n;
        //long temp1;
        while(temp>(9*pow(10,b-1)*b))
        {
            temp-=9*pow(10,b-1)*b;
            b++;
        }
        
        int p=temp%b;//余的位数
        ans=pow(10,b-1)+temp/b;
        int t=b-p+1;
        if(p==0)
        {
            ans--;
            t=1;
        }
        for(int i=0;i<t;i++)
        {
            ans1=ans%10;
            ans/=10;
        }
        return ans1;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值