/** * 蛇形矩阵 * 当输入5时,应该输出的三角形为: * 1 3 6 10 15 * 2 5 9 14 * 4 8 13 * 7 12 * 11 */ import java.util.Scanner; public class Test1{ public static void main(String[] args){ Scanner in = new Scanner(System.in); while(in.hasNextInt()){ int n = in.nextInt(); //读入正整数n int[][] result = new int[n][]; //建立数组(n行) int t = 1; //记录依次赋予的数组值 for(int i=0; i < n; i++){ result[i] = new int[n-i]; //数组第i行有n-i个元素 for(int j=0; j < i+1; j++){ //对第i个对角线赋值 result[i-j][j] = t; t++; } } //输出数组值 for(int[] a : result){ for(int a1 : a) System.out.print(a1 + " "); System.out.println(); } } } }
/** * 统计每个月兔子的总数 * 题目描述 有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问第n个月的兔子总数为多少? */ import java.util.*; public class Test2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ System.out.println(solution(scanner.nextInt())); } } private static int solution(int month) { // 第一个月初始化 // 一月龄兔子总数 int oneMonth = 1; // 二月龄兔子总数 int twoMonth = 0; // 三月龄及以上兔子总数 int threeMonth = 0; // 下个月将繁殖的兔子数量 int addVal = 0; // 第二个月开始递推, i表示第i个月 for(int i = 2; i <= month; i++) { // 三月龄及以上兔子总数 = 二月龄兔子总数 + 原本三月龄及以上兔子总数 threeMonth += twoMonth; // 二月龄兔子总数 = 上个月的一月龄兔子总数 twoMonth = oneMonth; // 一月龄(即这个月出生)兔子总数 = 上个月将繁殖的兔子数量 oneMonth = addVal; // 下个月将出生的兔子 = 下个月成为三月龄及以上的兔子数量 addVal = twoMonth