欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

打印从1到最大的n位数(Java实现)

程序员文章站 2024-03-15 22:08:36
...

public class E17Print1ToMax {
    //打印从1到最大的n位数
    //用字符数组解决大数问题

    public static void print1ToMaxN_Solution1(int n){
        //循环实现
        if (n <= 0)
            return;
        //初始化,索引0处存放个位数
        char[] bits = new char[n + 1];
        for (int i = 0; i <= n; i ++)
            bits[i] = '0';
        //当第n+1位没有进位时打印
        while(bits[n] == '0'){
            printNumber(bits, n);
            //将数字加1
            addNumber(bits, n);
        }

    }

    private static void addNumber(char[] bits, int n){
        for (int i = 0; i <= n; i++){
            //避免进位时char类型越界,将该位数字保存到int类型中
            int number = bits[i] - '0';
            number++;
            if (number >= 10){ //进位
                bits[i] = '0';
            }
            else{ //不能进位时跳出循环
                bits[i] += 1;
                break;
            }
        }
    }

    private static void printNumber(char[] bits, int n){
        //从第一个不为0的位开始打印
        StringBuilder number = new StringBuilder();
        for (int i = n - 1; i >= 0; i--){
            if (bits[i] != '0'){
                while(i >= 0){
                    number.append(bits[i]);
                    i--;
                }
            }
        }
        System.out.print(number + "\n");
    }

    public static void print1ToMaxN_Solution2(int n){
        //递归实现,全排列
        if (n <= 0)
            return;
        //初始化,索引0处存放个位数
        char[] bits = new char[n];
        for (int i = 0; i < n; i ++)
            bits[i] = '0';
        //排列
        for (int i = 0; i < 10; i++){
            bits[n - 1] = (char) (i + '0');
            print1ToMaxNCore(bits, n, n - 2);
        }
    }

    private static void print1ToMaxNCore(char[] bits, int n, int index){
        //每次递归结束时打印数字
        if (index == -1){
            printNumber(bits, n);
            return;
        }
        for (int i = 0; i < 10; i++){
            bits[index] = (char) (i + '0');
            print1ToMaxNCore(bits, n, index - 1);
        }
    }

    //测试用例
    public static void main(String[] args){
        char[] c = {'9', '1', '0', '3', '1', '0', '0', '0',};
        E17Print1ToMax.printNumber(c, 8);

        E17Print1ToMax.print1ToMaxN_Solution1(6);
        E17Print1ToMax.print1ToMaxN_Solution2(6);
    }
}
相关标签: 剑指offer 算法