输出斐波那契三角形

-----------金山云秋招笔试编程题
示例
输入:7
输出:
1
1 1 1
1 1 2 1 1
1 1 2 3 2 1 1
1 1 2 3 5 3 2 1 1
1 1 2 3 5 8 5 3 2 1 1
1 1 2 3 5 8 13 8 5 3 2 1 1

                                   ----java代码
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner in = new  Scanner(System.in);
		int n = Integer.parseInt(in.nextLine());
		method(n);
	}
	
	private static void method(int n) {
		StringBuilder sb = new StringBuilder();
		for(int i=0;i<n;i++) {
			int col = 2*(i+1)-1;
			int[] a = new int[col];
			//每一行输出先用数组遍历,
			//再把每个元素放到stringbuilder里
			if(col==1) {
				sb.append(1);
			}else {
				int n1 = 1,n2 = 1;
				a[0] = 1;
				a[1] = 1;
				sb.append(1).append(" ");
				sb.append(1).append(" ");
				for(int j=2;j<col;j++){
					if(j<=col/2) {
						a[j] = n1+n2;
						n1 = n2;
						n2 = a[j];
						sb.append(a[j]).append(" ");
					}else {
						a[j] = a[col/2-(j-col/2)];
						sb.append(a[j]).append(" ");
					}
				}
			}
			System.out.println(sb);//每次输出一行
			sb.delete(0, sb.length());//然后将StingBuilder清空
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值