LeetCode每日一题:第N个数字(No.400)

栏目: 编程工具 · 发布时间: 6年前

在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 个数字。
复制代码

示例:

输入:
3
输出:
3

输入:
11
输出:
0

说明:
第11个数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是0,它是10的一部分。
复制代码

思考:

这题先找规律:
1位数:1~9     总共1 * 9 = 9个数字
2位数:10~99   总共2 * 90 = 180个数字
3位数:100~999 总共3 * 900 = 2700个数字
...
digit位数:1 * Math.pow(10,digit-1) ~  Math.pow(10,digit) - 1 总共digit * 9 * Math.pow(10,digit - 1)个数字
所以根据n先判断在几位数的区间里,比如11在两位数10~99的区间里。
再把从1位数到digit位之前的数字个数都减去,得到在digit位数区间中相对位置。
因为digit位数中每个数的长度都为digit,再根据相对位置找到对应数字 。
复制代码

实现:

class Solution {
    public int findNthDigit(int n) {
        //几位数
        int digit = 1;
        //digit位数有多少数字
        int numCount = 9;
        //当n大于numCount时,
        while (n > numCount) {
            //从n中减去numCount个数字
            n -= numCount;
            //位数+1
            digit++;
            //计算新位数的数字个数
            numCount = (int) (9 * Math.pow(10, digit - 1) * digit);
        }
        //此时n已经是对应区间的相对位置
        //计算相对位置在第几个数上
        int quotient = n / digit;
        //计算余数
        int remainder = n % digit;
        //计算具体数值
        int num = (int) (1 * Math.pow(10, digit - 1) + quotient - 1);
        if (remainder == 0) {//余数为0,说明正好是num的最后一位
            char[] array = String.valueOf(num).toCharArray();
            return Integer.parseInt(String.valueOf(array[array.length - 1]));
        } else {//余数不为0,说明是下一位数中的数字
            String numStr = String.valueOf(num + 1);
            char[] array = numStr.toCharArray();
            //根据余数获得对应数字
            return Integer.parseInt(String.valueOf(array[remainder - 1]));
        }
    }
}复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Developing Large Web Applications

Developing Large Web Applications

Kyle Loudon / Yahoo Press / 2010-3-15 / USD 34.99

As web applications grow, so do the challenges. These applications need to live up to demanding performance requirements, and be reliable around the clock every day of the year. And they need to withs......一起来看看 《Developing Large Web Applications》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具