【LeetCode】400 Nth Digit(java实现)

原题链接

https://leetcode.com/problems/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.

题目要求

题目叫“第N个数字”,有一个从1到无限大的整形列表:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …,求出第n个单数字。比如说第3个单数字是3,而第10个单数字是10的十位数,第11个单数字是10的个位数, 第12个单数字是11的十位数,以此类推。
为了避免混淆,我先说几个我定义的概念,便于理解。实际数字,值得是这个整形列表中的实际数据,从1到无穷大;单数字指的是实际数字的每个位数,如实际数字23有两个单数字,分别为2和3。

解法

解法:这里有这样一个规律,从1到9,有9个只占1个位数的数字,数字个数为10 - 1 + 1;从10到99,有90个占2个位数的数字,数字个数为99 - 10 + 1,因此可以得到这样的规律:

范围占位个数共占位
1——919-1+1 = 99*1=9
10——99299-10+1=9090*2=180
100——9993999-100+1=900900*3=2700
……

因此,如果要超照第n个单数字,首先要算出这个数字在哪个区间范围,在该范围内每个实际的数字占几个位,这个范围内第一个实际数字前已经占用了多少个单数字。然后,根据这些数据求出具体的值。

public int findNthDigit(int n){
    // 该范围内所有实际数字都占用了digit个单数字
    int digit = 1;
    // 该范围之前的所有实际数字已经占用了totalDigit个单数字
    long totalDigit = 0;
    // 先查出区间范围
    while (true) {
        long top = totalDigit + digit * 9 * (long)Math.pow(10, digit -1);
        if(n >= totalDigit && n <= top)
            break;
        totalDigit = top;
        digit++;
    }

    // 根据范围算出具体的值
    int start = (int)Math.pow(10, digit - 1);
    int ret = 0;
    totalDigit += 1;
    // 第n个digit在哪个具体的实际数字上
    int value = start + (n - (int)totalDigit) / digit;
    ret = Integer.toString((int)value).charAt((int)((n - totalDigit)%digit)) - '0';
    return ret;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值