题目:
数字以0123456789101112131415……的格式序列化到一个字符序列中。在这个序列中,第5位(从0开始计数)是5,第19位是4。请写一个函数,求任意第n为对应的数字。
分析:
假设要找地1001位数字,序列的前10位是0~9折10个只有1位的数字,1001位在这10个数字之后,从这个位置继续找1001-10=991位数字,后面的180位数字是90个10~99的两位数,991>180,继续向后找991-180=811位数字,接下来2700位是900个100~999的三位数,由于2700>811,所以第811位是某个三位数中的一位,由于811=270×3+1,于是第811位是从100开始的第270个数的第一位(从0开始计数),也就是370的第一位(从0开始计数)就是7了。
解法:
package com.wsy;
public class Main {
public static void main(String[] args) {
int n = 1001;
getDigitalOfN(n);
}
public static void getDigitalOfN(int n) {
int index = 1;// 当前走到哪一位了,1:个位,2:十位,3:百位……
int numbers = index * countOfInteger(index);
while (n >= numbers) {// 每次跳过index * countOfInteger(index)个
n -= numbers;
index++;
numbers = index * countOfInteger(index);
}
int number;// n被卡在了具体哪个数字上
if (index == 1) {
number = 0;
} else {
number = (int) Math.pow(10, index - 1);
}
number += n / index;
int indexFromRight = index - n % index;// 第n个位置在数字number上的下标,这个下标是从右侧开始计的
for (int i = 1; i < indexFromRight; i++) {
number /= 10;
}
System.out.println("第" + n + "位数字是:" + number % 10);
}
/**
* n=1:0~9:10个
* n=2:10~99:90个
* n=3:100~999:900个
* n=4:1000~9999:9000个
*/
public static int countOfInteger(int n) {
if (n == 1) {
return 10;
}
return (int) (9 * Math.pow(10, n - 1));
}
}