The sword refers to Offer-question 17 (Java Edition): print 1 to the largest n digits

Reference from: "Sword Pointing Offer - Famous Enterprise Interviewer Talking About Typical Programming Questions"

Question : Print 1 to the largest n digits
Enter number n and print out the decimal digits from 1 to the largest in order. For example, if you enter 3, it will print out 1, 2, 3 up to the largest 3-digit number, which is 999.

The main idea : The n digits from 1 to the largest are actually n full permutations from 0 to 9. Arrange each digit from 0 to 9 to get all the numbers. The total number is 10 n . Full permutation can be achieved using recursion.

Key point : recursion

Time complexity : O( 10 n )

public class PrintOneToMaxOfNDigits
{
    public static void main(String[] args)
    {
        int n = 3;
        print1ToMaxOfNDigits(n);
    }

    private static void print1ToMaxOfNDigits(int n)
    {
        if (n <= 0)
            return;

        char[] numbers = new char[n];

        for (int i = 0; i < 10; ++i)
        {
            numbers[0] = (char) (i + '0');
            printByRecursively(numbers, n, 0);
        }

    }

    private static void printByRecursively(char[] numbers, int length, int index)
    {
        if (index == length - 1)
        {
            printNumber(numbers);  //递归到数字长度为n,则打印结果
            return;
        }

        for (int i = 0; i < 10; ++i)
        {
            numbers[index + 1] = (char) (i + '0');
            printByRecursively(numbers, length, index + 1);
        }
    }

    private static void printNumber(char[] numbers)
    {
        boolean isBeginWithZero = true;
        for (char number : numbers)
        {
            //忽略开头的0
            if (isBeginWithZero && number != '0')
                isBeginWithZero = false;

            if (!isBeginWithZero)
            {
                System.out.print(number);
            }
        }
        System.out.println();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325982275&siteId=291194637