Article Directory
A digital bit sequence of numbers: 44 face questions
One, Title Description
0123456789101112131415 ... in digital format into a sequence of character sequence. In this sequence, bit 5 (counting from 0) is 5, the 13th bit is 1, 4 bits are 19, and the like. Please write a function corresponding seeking any bit digital.
Second, the problem analysis
The search for effective solutions, but also find the law:
- Digit number a total of 10, i.e. 0 to 9, * 1 accounted for 10 digits; (special)
- A two-digit number a total of 90, i.e. 10 to 99, each figure represents two, accounting for a total of 90 * 2 digits;
- ……
- A total number m of bits of the 9 * 10 ^ (m-1) th, m bits representing each number, representing 9 * 10 ^ (m-1) * m bit number.
Analyzing the n-th number belongs to a few, then to find the number of several.
For example:
0123456789101112131415161718192021 ...
We want to take the first 33.
For more images, we put the law above abstract scene into a more intuitive: we want to put actual figures are stored in a squares inside. A plurality of digital grid may be stored.
First of all we want to find the first 33-digit number that corresponds to the character. Since the number of digits are 10, 90 have a double-digit number, 33 interposed between 10-100, two may be determined.
A storage box using two features:
(33-10) / 2 stars 11, 10 will come together with figure 33 corresponding to the character of the number is 21
(33-10) we come to 2% corresponding character bit, i.e., a first digital
Third, questions
public int digitAtIndex(int index) {
if(index<0){
return -1;
}
// m位数
int m=1;
while(true) {
// m位数的个数
int numbers=numbersOfIntegers(m);
if(index<numbers*m) {
return getDigit(index,m);
}
index-=numbers*m;
m++;
}
}
// 返回m位数的总个数
private int numbersOfIntegers(int m) {
if(m == 1) {
return 10;
}
return (int) (9*Math.pow(10, m-1));
}
// 获取数字
private int getDigit(int index, int m) {
// 对应的m位数
int number = getFirstNumber(m)+index/m;
// 在数字中的位置
int indexFromRight = m - index%m;
for(int i=1; i < indexFromRight; i++) {
number/=10;
}
return number%10;
}
// 第一个m位数 例如第一个两位数是10,第一个三位数是100
private int getFirstNumber(int m) {
if(m==1) {
return 0;
}
return (int) Math.pow(10, m-1);
}