剑指Offer Java版 面试题17:打印从1到最大的n位数

题目:输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印出1、2、3一直到最大的3位数999。

方法1:遍历

public void print1ToMaxOfNDigits(int n) {
    if (n <= 0) {
        return;
    }
    char[] number = new char[n];
    for (int i = 0; i < n; i++) {
        number[i] = '0';
    }
    while (!increment(number)) {
        printNumber(number);
    }
}

private boolean increment(char[] number) {
    int takeOver = 0;
    int length = number.length;
    for (int i = length - 1; i >= 0; i--) {
        int sum = number[i] - '0' + takeOver;
        if (i == length - 1) {
            sum++;
        }
        if (sum >= 10) {
            if (i == 0) {
                return true;
            } else {
                sum -= 10;
                takeOver = 1;
                number[i] = (char) ('0' + sum);
            }
        } else {
            number[i] = (char) ('0' + sum);
            break;
        }
    }
    return false;
}

private void printNumber(char[] number) {
    boolean isBegin0 = true;
    int length = number.length;
    for (int i = 0; i < length; i++) {
        if (isBegin0 && number[i] != '0') {
            isBegin0 = false;
        }
        if (!isBegin0) {
            System.out.print(number[i]);
        }
    }
    if (!isBegin0) {
        System.out.println();
    }
}

方法2:递归

public void print1ToMaxOfNDigits(int n) {
    if (n <= 0) {
        return;
    }
    char[] number = new char[n];
    for (int i = 0; i < 10; i++) {
        number[0] = (char) (i + '0');
        print1ToMaxOfNDigitsRecursively(number, n, 0);
    }
}

private void print1ToMaxOfNDigitsRecursively(char[] number, int length, int index) {
    if (index == length - 1) {
        printNumber(number);
        return;
    }
    for (int i = 0; i < 10; i++) {
        number[index + 1] = (char) (i + '0');
        print1ToMaxOfNDigitsRecursively(number, length, index + 1);
    }
}

private void printNumber(char[] number) {
    boolean isBegin0 = true;
    int length = number.length;
    for (int i = 0; i < length; i++) {
        if (isBegin0 && number[i] != '0') {
            isBegin0 = false;
        }
        if (!isBegin0) {
            System.out.print(number[i]);
        }
    }
    if (!isBegin0) {
        System.out.println();
    }
}

剑指Offer Java版目录
剑指Offer Java版专题

你可能感兴趣的:(剑指Offer Java版 面试题17:打印从1到最大的n位数)