package test;

import org.junit.Test;
import quicksort.Solution;

/*
* 实现从1输出到最大的n位数
*/

public class SloutionForOneToN {
    public void printNumbers(int n) {
        //创建一个n位的全0数,最低位在最右边,这样方便输出
       int[] res = new int[n];
        //当没有发生溢出时, 每计算完一个数就打印一个数字
        while(!caluateNumber(res)){
            int idx = 0;
            //不打印前面的'0'
            while(idx<res.length&&res[idx]==0){
                idx++;
            }
            StringBuilder temp = new StringBuilder();
            for(int i=idx;i<res.length;i++){
                temp.append(res[i]);
            }
            System.out.println(temp.toString());
        }

    }
    public boolean caluateNumber(int[] res){//返回值表示是否发生了溢出
        //执行大数加法,每次令当前数字加1
        int idx = res.length-1;
        int jw = 0;
        res[idx]+=1;
        if(res[idx]>=10){
            jw = res[idx]/10;
            res[idx]=res[idx]%10;
            idx--;//计算下一位
            while(jw>0){
                if(idx==-1){//表示发生溢出,直接return true
                    return true;
                }
                res[idx]+=1;
                jw = res[idx]/10;
                res[idx]=res[idx]%10;
                idx--;//计算下一位
                }
            }
        return false;
    }

    public static void main(String[] args) {
        SloutionForOneToN s = new SloutionForOneToN();
        s.printNumbers(3);
    }
}


版权声明:本文为weixin_44718747原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_44718747/article/details/107583037