A number in a sequence of numbers (Java)

A number in a sequence of numbers (Java)

Title: A
digit in a digit sequence is
serialized into a character sequence in the format of 0123456789101112131415 ... In this sequence, the 5th bit (counting from 0) is 5, the 13th bit is 1, the 19th bit is 4, and so on. Please write a function to find the number corresponding to any digit.
Idea: For
example analysis, for example, to find the 1001th digit,
1) There are 10 1-digit values: 0 ~ 9, the number is 10 × 1 = 10, obviously 1001> 10, skip these 10 values, and then Find the 991th (1001-10) digit.
2) There are 90 2-digit values: 10 ~ 99, the number is 90 × 2 = 180, and 991> 180, continue to find the 811 (991-180) digits in the back.
3) There are 900 3-digit values: 100 ~ 999, the number is 900 × 3 = 2700, and 811 <2700, indicating that the 811th digit is in the value with 3 digits. Since 811 = 270 × 3 + 1, the 811th digit is the 270th numeric value starting from 100, or the second digit of 370, which is 7.
According to this rule, other figures can be obtained.
Code:

public class DigitsInSequence
{
    public static void main(String[] args)
    {
        System.out.println(digitAtIndex(9)); //9
        System.out.println(digitAtIndex(189)); //数字99的最后一位:9
        System.out.println(digitAtIndex(190)); //数字100的第一位:1
    }

    private static int digitAtIndex(int index)
    {
        if (index < 0) return -1;
        int digits = 1;
        while (true)
        {
            int digitNumbers = countOfNumbersFor(digits); //当前位数的数值个数
            //数值乘上它的位数等于数字个数,
            //比如,两位数有90个(10~99),每个数值有2个数字,总数字个数为180
            int countOfNumbers = digitNumbers * digits;
            if (index < countOfNumbers)
            {
                return digitAtIndex(index, digits);
            } else
            {
                //在下一位中查找
                index -= countOfNumbers;
                digits++;
            }
        }
    }

    //digits位数的数字个数,
    //两位数有9*10=90个(10~99),三位数有9*100=900个(100~999)
    private static int countOfNumbersFor(int digits)
    {
        if (digits == 1)
            return 10;

        int count = (int) Math.pow(10, digits - 1);
        return 9 * count;
    }

    private static int digitAtIndex(int index, int digits)
    {
        //对应的数值
        int number = beginNumberFor(digits) + index / digits;
        //从数值右边开始算的位置
        int indexFromRight = digits - index % digits;
        //去除右边的indexFromRight-1个数字
        for (int i = 1; i < indexFromRight; i++)
            number /= 10;
        //求个位数字
        return number % 10;
    }

    //digits位数的第一个数字,两位数从10开始,三位数从100开始
    private static int beginNumberFor(int digits)
    {
        if (digits == 1)
            return 0;

        return (int) Math.pow(10, digits - 1);
    }
}
Published 71 original articles · praised 0 · visits 878

Guess you like

Origin blog.csdn.net/sinat_40968110/article/details/105482321