力扣每日一题2021-11-30第N位数字

力扣每日一题2021-11-30第N位数字,第1张

力扣每日一题2021-11-30第N位数字

第N位数
  • 400.第N位数字
    • 题目描述
    • 思路
      • 模拟
        • Python实现
        • Java实现


400.第N位数字 题目描述

第N位数字


思路 模拟

很容易能发现如下规律:

1位数有9个,共有19个数字
2位数有90个,共有2
90个数字
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)) % 10
Java实现

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;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5624748.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存