0
点赞
收藏
分享

微信扫一扫

【LeeCode】400. 第 N 位数字

腊梅5朵 2023-03-17 阅读 72

【题目描述】

给你一个整数 ​n​ ,请你在无限的整数序列 ​[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]​ 中找出并返回第 ​n​ 位上的数字。

​​​https://leetcode.cn/problems/nth-digit/description/​​​

【示例】

【LeeCode】400. 第 N 位数字_Math


【代码】​​直接计算​​

​​题意理解​​看了这个图才知道一个无限的数, 第11位为是0, 因为第10位是1, 前9位分别是1, 2, 3, 4 ... 9

【LeeCode】400. 第 N 位数字_git_02

package com.company;
// 2023-03-17
import java.util.*;

class Solution {
public int findNthDigit(int n) {
int d = 1;
int count = 9;
// 如果一个三位数,
// n = 365 - 9 - 2 * 9 * 10
while (n > (long) d * count){
n -= d * count;
d++;
count *= 10;
}
// 这时 n=176 表示目标数字是三位数中的第 176 个数字。
int index = n - 1;
// 计算开始值, 此时 d = 3 , pow(10, 3-1)从100开始
int start = (int) Math.pow(10, d - 1);

// number = 100 + 176/3 = 158
int num = start + index / d;

// 第三步: 计算目标数字num对3取余是2, 即是158的第位
int digIndex = index % d;
// 计算第2位的数是什么
int digit = (num / (int)(Math.pow(10, d - digIndex - 1))) % 10;
// System.out.println(digit);
return digit;

}
}


public class Test {
public static void main(String[] args) {
new Solution().findNthDigit(365); // 输出:3
new Solution().findNthDigit(3); // 输出:3
new Solution().findNthDigit(11); // 输出: 0
new Solution().findNthDigit(1000000000); // 输出: 1
}
}

举报

相关推荐

0 条评论