题目
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4等等。请写出一个函数,求任意第n位对应的数字。
解题思路
比如,序列的第1001位是什么?
序列的前10位是0-9这10个只有一位的数字。显然第1001位在这10个数字之后,因此这10个数字可以直接跳过。我们再从后面紧跟着的序列中找第991(991=1001-10)位的数字。
接下来180位数字是90个10-99的两位数。由于991>180,所以第991位的所有的两位数之后。我们再跳过90个两位数,继续从后面找881(881=991-180)位。
接下来的2700位是900个100-999的三位数。由于881<2700,所以第881位是某个三位数中的一位。由于881=270X3+1,这就意味着第881位是从100开始的第270个数字即370的中间一位,也就是7。
源代码
package Arithmetic;
public class GetDigitAtIndex {
public static int getDigitAtIndex(int index) {
if (index < 0)
return -1;
int place = 1;//1表示个位,2表示十位
while (true) {
int amount = getAmountOfPlace(place);
int totalAmount = amount * place;//place位数字组成的字符串的总长度
if (index < totalAmount)//检索的字符位置小于总的字符串长度
return getDigitAtIndex(index, place);
index -= totalAmount;
place++;
}
}
//在place位数组成的字符串中,第index个数
private static int getDigitAtIndex(int index, int place) {
int startNumber = getBeginNumberOfPlace(place);//place位数的起始数字
int shiftNumber = index / place;//从起始数开始,偏移的数字
String number = (startNumber + shiftNumber) + "";//第index位数字所在的place位数字
int count = index % place;//第index位数所在place位数中的位置
return number.charAt(count) - '0';//返回该位置的数字
}
//place位数组成的整数的起始数字
private static int getBeginNumberOfPlace(int place) {
if (place == 1)
return 10;
return (int) Math.pow(10, place - 1);
}
//place位数的数字总数
private static int getAmountOfPlace(int place) {
if (place == 1)
return 10;
return (int) Math.pow(10, place - 1) * 9;
}
public static void main(String[] args) {
System.out.println(getDigitAtIndex(5));
}
}