打印1到最大的n位数

package testcase;

/**
 * 
 * @decription 打印1到最大的n位数
 * @author bjliuzezhou
 * @date 2016年2月24日
 */
public class TypicalArithmetic_04 {

    private static int newLine = 0;
    
    public static void main(String[] args) {
        
        int n=3;
        String s = Increment(getInputString(n));
        PrintNumber(s);
        s = Increment(s);
         
        //判断是否达到最大n位数 
        //如果字符串再次返回类似"000",则说明已经达到了最大n位数
        while(!s.equals(getInputString(n))){
            
             PrintNumber(s);
             s = Increment(s);
        }
        
    }

    //根据要打印的最大n位数  确定输入"00"(n=2) 还是"000"(n=3)
    public static String getInputString(int n){
        String s = "";
        for(int i=0; i<n; i++){
            s+="0";
        }
        return s;
    }
    
    
    //模拟字符串自增
    public static String Increment(String s){
        
        char ch[] = new char[s.length()];
        int sum = 0;
        int Len = s.length();
        for(int i=Len-1; i>=0; i--){
            ch[i] = s.charAt(i);
        }
        
        for(int i=Len-1; i>=0; i--){
            
            sum = ch[i] - '0' + 1;
            if(sum==10){
                ch[i] = '0';
            }else{
                ch[i] = (char)(sum+'0');
                break;
            }
        }
        
        String tmp="";
        for(int i=0; i<Len; i++){
            tmp+=ch[i];
        }
        return tmp;
    }
    
    
    //打印字符串   
    public static void PrintNumber(String s){
        
        boolean firstLetter = true;
        
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            //如012不能打印前面的0   只打印12
            if (firstLetter == true) {
                if (ch != '0') {
                    System.out.print(ch);
                    firstLetter = false;
                }
            } else {
                System.out.print(ch);
            }
            
        }
        
        //调整输出格式   变得好看一点
        System.out.print(" ");
        newLine++;
        if(newLine==100){
            System.out.println("\n");
            newLine = 0;
        }
    }
}

 

posted @ 2016-03-02 11:19  苍穹冰尘  阅读(239)  评论(0编辑  收藏  举报
Live2D