- 400.第N位数字
- 题目描述
- 思路
- 模拟
- Python实现
- Java实现
400.第N位数字 题目描述
第N位数字
思路 模拟
很容易能发现如下规律:
1位数有9个,共有19个数字
2位数有90个,共有290个数字
3位数有900个,共有3*900个数字
…
如果想知道第N为数字,相当于要找到它是几位数,在那位数中是第几个数字,然后找到这个数字的第几位。
Python实现class Solution: def findNthDigit(self, n: int) -> int: cur, base = 1, 9 while n > cur * base: n -= cur * base cur += 1 base *= 10 n -= 1 num = 10 ** (cur -1) + n // cur idx = n % cur return num // (10 ** (cur - 1 - idx)) % 10Java实现
class Solution { public int findNthDigit(int n) { int cur = 1, base = 9; while (n > cur * base) { n -= cur * base; cur ++; base *= 10; if (Integer.MAX_VALUE / base < cur) { break; } } n --; int num = (int)Math.pow(10, cur-1) + n / cur, idx = n % cur; return num / (int)Math.pow(10, cur - 1 - idx) % 10; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)