题目
给你一个整数 n
,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]
中找出并返回第 n
位上的数字。
示例 1:
输入:n = 3 输出:3 示例 2:
输入:n = 11 输出:0 解释:第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是 0 ,它是 10 的一部分。
提示:
1 <= n <= 231 - 1
第
n
位上的数字是按计数单位(digit)从前往后数的第n
个数,参见 示例 2 。
题解
法一
利用字符串和包装类的知识但是n=10000000时会超出内存限制(捂脸)
class Solution { public int findNthDigit(int n) { //利用字符串和包装类求解 StringBuilder sb=new StringBuilder(); int i=1; //第n位数字肯定在n个数拼接范围内出现 while(i<=n){ sb.append(Integer.toString(i)); i++; } String s=sb.toString(); //注意在字符串内的索引为n-1 return Integer.parseInt(String.valueOf(s.charAt(n-1))); } }
法二
-
求出n所在的范围即位数:某位数的数字个数满足9*位数;
-
求出n所在的数字
-
求出n在数字中的索引得到答案
class Solution { public int findNthDigit(int n) { if(n == 0) return 0; int len = 1; //一个数占len位,一开始占1位 long start = 1; //占len位的数的起点 long count = 9; //占len位的数有count个 while(n > len * count){ //求出n所在的数字范围 n -= len * count; len++; start=start*10; count=count*10; } //求出n所在的数字 String number = String.valueOf(start + (n - 1) / len); //因为n从1开始计数,所以-1 //求出第n位所在数字的索引 int index = (n - 1) % len; return Integer.parseInt(String.valueOf(number.charAt(index))); } }