[LeetCode]--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).Exampl

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,3,4,5…这样的数列,n<9时,自然得出来的就是数列中数,但是到了10就有两位,到了100就有三位,而这个n是表示位数,所以11就是10的那个零,结果返回0。

分析规律
个位数 是1-9 bit范围 9
两位数 10-99bit范围 2*90
三位数 100-999范围 3*900
…………
先确定给定值在哪个范围内 找出此范围的起始值10^n
注意取位置时减1 再进行操作
需要注意越界问题 count*10 9一直乘10 所以会越界 处理越界用long型

public int findNthDigit(int n) {
        int len = 1;
        long count = 9;
        int start = 1;

        while (n > len * count) {
            n -= len * count;
            len += 1;
            count *= 10;
            start *= 10;
        }
        start += (n - 1) / len;
        String s = Integer.toString(start);
        return Character.getNumericValue(s.charAt((n - 1) % len));
    }
目录
相关文章
LeetCode 400. Nth Digit
在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 个数字。
204 0
LeetCode 400. Nth Digit
LeetCode 233. Number of Digit One
给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。
185 0
LeetCode 233. Number of Digit One
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
|
Java Python
LeetCode 19:删除链表的倒数第N个节点 Remove Nth Node From End of List
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 Given a linked list, remove the n-th node from the end of list and return its head. 示例: 给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5. 说明: 给定的 n 保证是有效的。
986 0
[LeetCode] Number of Digit One
The following idea is taken from a book named 《剑指offer》 published in China. Suppose n = 271, it then breaks [1, 271] into [1, 71] and [72, 271].
794 0
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
254 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行

热门文章

最新文章