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

java实现杨辉三角算法

程序员文章站 2024-03-15 16:10:41
...
public class Test {
	private static int[][] allNum;
	private static int[] eachLayerNum;
	
	public static void main(String[] args) {
    	//层数
        int layerNum = 0;
        Scanner sc = new Scanner(System.in);
       	System.out.println("请输入打印行数:");
        layerNum = sc.nextInt();
        //执行计算
        handle(layerNum);
        //输出
        output();
	}
        
    public static void handle(int layerNum){
    	allNum = new int[layerNum][];
        for (int i = 0; i < layerNum; i++){
        	eachLayerNum = new int[i+1];
            if (i > 0){
            	for (int j = 0; j<=i; j++){
                	if (j == 0){
                    	eachLayerNum[j] = allNum[i-1][j];
                    }else if (j == i){
                    	eachLayerNum[j] = allNum[i-1][j-1];
                    }else{
                   		eachLayerNum[j] = allNum[i-1][j-1] + allNum[i-1][j];
                    }
                }
			}else{
            	eachLayerNum[i] = 1;
            }
           	allNum[i] = eachLayerNum;
        }
    }

	public static void output(){
		for (int i = 0; i < allNum.length; i++){
        	for (int j = i; j < allNum.length-1; j++){
            	System.out.print("   ");
          	}
            for (int j = 0; j < allNum[i].length; j++){
            	if (allNum[i][j] < 10){
                	System.out.print("    ");
                }else if(allNum[i][j] >= 10 && allNum[i][j] < 100) {
                	System.out.print("   ");
                }else if(allNum[i][j] >= 100&&allNum[i][j] < 1000){
                	System.out.print("  ");
                }else{
                	System.out.print(" ");
                }
               	System.out.print(allNum[i][j]);
                System.out.print(" ");
            }
            System.out.println();
        }
	}
}

java实现杨辉三角算法
java实现杨辉三角算法

相关标签: java 算法