本系列導(dǎo)航:劍指offer(第二版)java實現(xiàn)導(dǎo)航帖
面試題44:數(shù)字序列中某一位的數(shù)字
題目要求:
數(shù)字以01234567891011121314...的格式排列。在這個序列中,第5位(從0開始計)是5,第13位是1,第19位是4。求任意第n為對應(yīng)的數(shù)字。
解題思路:
與43題類似,都是數(shù)學(xué)規(guī)律題。如果用遍歷的方式,思路代碼都很簡單,但速度較慢。更好的方式是借助于數(shù)字序列的規(guī)律,感覺更像是數(shù)學(xué)題。步驟大致可以分為如下三部分:
以第15位數(shù)字2為例(2隸屬與12,兩位數(shù),位于12從左側(cè)以0號開始下標(biāo)為1的位置)
步驟1:首先確定該數(shù)字是屬于幾位數(shù)的;
如果是一位數(shù),n<9;如果是兩位數(shù),n<9+90*2=189;
說明是兩位數(shù)。
步驟2:確定該數(shù)字屬于哪個數(shù)。10+(15-10)/2= 12。
步驟3:確定是該數(shù)中哪一位。15-10-(12-10)*2 = 1, 所以位于“12”的下標(biāo)為1的位置,即數(shù)字2。
以第1001位數(shù)字7為例
步驟1:首先確定該數(shù)字是屬于幾位數(shù)的;
如果是一位數(shù),n<9;如果是兩位數(shù),n<9+90*2=189;如果是三位數(shù),n<189+900*3=2889;
說明是三位數(shù)。
步驟2:確定該數(shù)字屬于哪個數(shù)。100+(1001-190)/3= 370。
步驟3:確定是該數(shù)中哪一位。1001-190-(370-100)*3 = 1,所以位于“370”的下標(biāo)為1的位置,即數(shù)字1。
package chapter5;
/**
* Created with IntelliJ IDEA
* Author: ryder
* Date : 2017/8/3
* Time : 8:50
* Description:數(shù)字序列中某一位的數(shù)字
**/
public class P225_DigitsInSequence {
public static int digitAtIndex(int index){
if(index<0)
return -1;
if(index<10)
return index;
int curIndex = 10,length = 2;
int boundNum = 10;
while (curIndex+lengthSum(length)<index){
curIndex+=lengthSum(length);
boundNum*=10;
length++;
}
int addNum = (index-curIndex)/length;
int curNum = boundNum + addNum;
return Integer.toString(curNum).charAt(index-curIndex-addNum*length)-'0';
}
public static int lengthSum(int length){
int count = 9;
for(int i=1;i<length;i++)
count*=10;
return count*length;
}
public static void main(String[] args){
for(int i=9;i<16;i++)
System.out.println(digitAtIndex(i));
System.out.println(digitAtIndex(1001));
}
}
運(yùn)行結(jié)果
9
1
0
1
1
1
2
7