public static void main(String[] args) {
/*
* 这一段是测试代码
*/
StringBuffer stringBuffer = new StringBuffer();
for(int i = 1; i < 100000; i ++){
stringBuffer.append(i);
}
for(int i = 0; i < 10000; i ++){
int random = (int) (Math.random() * stringBuffer.length());
if(stringBuffer.charAt(random) - '0' != getNValue(random)){
System.out.println("error");
}
}
}
private static int getNValue(int n){
byte bit = 0;
//计算出n对应的位数
while(getLengthByBit(bit) <= n){
bit ++;
}
//减去前面bit-1位数字的总长度后的剩余长度
long leftLength = n - getLengthByBit(bit - 1);
//计算对应的值
int value = (int) (Math.pow(10, bit - 1) + leftLength / bit);
//取出数字
for(int i = 0; i < bit - 1 - leftLength % bit; i ++)
value /= 10;
value %= 10;
return value;