如何通过连续写入自然数来获得数字中的x(未知)数字:123456789101112

时间:2018-10-14 22:22:16

标签: c

我想用C语言做到这一点,而且我不想使用数组或字符串。

我已经使用数组完成了它,但是没有它,我不知道该怎么办。我只能使用循环和if。

1 个答案:

答案 0 :(得分:0)

我发现这是一个有趣的问题,并为此编写了完整的代码。如果您想自己做,那就不要研究代码。这里有一些提示:
1.我们知道有多少个一定长度的数字:9 1-digit numbers, 90 2-digits, 900 3-digits and so on
2.因此,我们可以找到由1、2和3位数字组成的数字在一起写多长时间:9*1 + 90*2 + 900*3 = 2889
3.这意味着,如果要求我们找到第253673位数字,则可以肯定地说它是4位数字中的一个数字,因为253673 > 38889253673 < 488889
4.现在,我们只需要查找该4位数字及其内部的一个数字。


现在,如果您只想要一个解决方案,那么这是我的代码,虽然它是C#,但是如果这不是关于C的错字,它应该真的很容易翻译。

    public static int GetDigit(long digitPosition)
    {
        if (digitPosition < 10)
            return (int) digitPosition;

        int N = 1;
        long lengthOfNumber = 9;
        int amountOfDigits = -1;
        while(lengthOfNumber < digitPosition)
        {
            N++;
            // there are 9 one-digit numbers, 90 two-digit numbers, 900 three-digit numbers and so on
            int amountOfNumbers = 9 * (int)Math.Pow(10, N - 1);
            // length of all N-digit numbers written together
            amountOfDigits = amountOfNumbers * N;
            // total length of composed number if we add all N-digit numbers
            lengthOfNumber += amountOfDigits;
        }
        // now we know how much digits has the sub-number with target digit inside the composed number

        // shift target digit position by removing all numbers below N length
        // so if the digitPosition was 14, it will become 5th position in the number created from only 2-digit numbers, because we subtract all 9 1-digit numbers
        digitPosition -= lengthOfNumber - amountOfDigits;
        // get index of N-digit number that contains target digit, starting from the first N-digit number (for N=3 it's)
        long numberIndex = (digitPosition - 1) / N;
        // get index of digit inside that number, that is our target digit
        long digitIndex = (digitPosition - 1) % N;
        // find the number that contains target digit by adding index to the first N-digit number
        long targetNumber = 1 * (long)Math.Pow(10, N - 1) + numberIndex;
        // shift target digit to the target position
        for (int i = 0; i < N - digitIndex - 1; i++)
            targetNumber /= 10L;

        // digit found
        return (int) (targetNumber % 10L);
    }