题目描述
数字以 0123456789101112131415… 的格式序列化到一个字符串中,求这个字符串的第 index 位。
题解
public class Solution {
public int getDigitAtIndex(int index)
{
if(index<0)
return -1;
int place = 1;
while (true)
{
int amount = getAmountOfPlace(place);
int totalAmount = amount*place;
if(index<totalAmount)
return getDigitAtIndex(index,place);
index -= totalAmount;
place++;
}
}
private int getAmountOfPlace(int place)
{
if(place==1)
return 10;
return (int) Math.pow(10,place-1)*9;
}
private int getBeginNumberOfPlace(int place)
{
if (place==1)
return 0;
return (int) Math.pow(10,place-1);
}
private int getDigitAtIndex(int index, int place)
{
int beginNumber = getBeginNumberOfPlace(place);
int shiftNumber = index/place;
String number = (beginNumber + shiftNumber) + "";
int count = index % place;
return number.charAt(count) - '0';
}
public static void main(String args[])
{
Solution a = new Solution();
System.out.println(a.getDigitAtIndex(1001));
}
}
本文介绍了一种算法,用于解决数字序列化成字符串后如何找到该字符串的任意指定位置上的数字。通过定义一系列辅助方法,如计算指定位数范围内数字的总数、获取指定位数的起始数字等,实现了高效查找。
488

被折叠的 条评论
为什么被折叠?



