剑指offer系列之11:打印1到最大的n位数

来源:互联网 发布:放置江湖轻功数据 编辑:程序博客网 时间:2024/06/14 03:40

题目描述:输入数字n,按顺序打印出从1到最大的n为十进制数,比如输入3,则从1一直打印输出到999.

思路1:该题最大的陷阱是没有规定n的范围,所以我么需要考虑大数问题,可以咋字符串上模拟数字的加法。函数increment使数字每次加1然后输出,函数output输出数字将高位的0舍掉。

package dsproblem;import java.util.ArrayList;import java.util.Iterator;public class Print1ToMaxOfNDigits {    public static void outPutOneToMaxNDigits(int n) {        // 用nlist表示数n,nlist[0]表示n的最低位        ArrayList<Integer> nlist = new ArrayList<Integer>();        for (int i = 0; i < n; i++) {            nlist.add(0);        }        increment(nlist);    }    // 使数字每次+1然后输出    public static void increment(ArrayList<Integer> nlist) {        int carrybit = 0;        boolean end = false;        while (true) {            for (int i = nlist.size() - 1; i >= 0; i--) {                int digit = nlist.get(i);                int sum = digit + carrybit;                if (i == (nlist.size() - 1)) {                    sum += 1;                }                if (sum >= 10) {                    // 最高位产生进位,达到最大值,停止输出                    if (i == 0) {                        end = true;                    }                    sum = sum - 10;                    carrybit = 1;                } else {                    carrybit = 0;                }                nlist.set(i, sum);            }            output(nlist);            if (end) {                break;            }        }    }    // 输出数字,将高位的0舍掉    public static void output(ArrayList<Integer> nlist) {        Iterator<Integer> ite = nlist.iterator();        int num;        // 找到第一个为0的位置        boolean first = false;        while (ite.hasNext()) {            if (first) {                System.out.print(ite.next());                continue;            }            if ((num = ite.next()) != 0) {                first = true;                System.out.print(num);            }        }        System.out.println();    }}

思路2:把问题转化为数字全排列的问题,使用递归能够使代码更加简洁。

0 0