链接
https://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e?tpId=37&tqId=21258&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fdifficulty%3D2%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=2&judgeStatus=undefined&tags=&title=
题目
代码
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num=sc.nextInt();
int[][]arr=new int[num][num];
int value=1;
for(int sum=0;sum<=num-1;sum++){
for(int x=0;x<=sum;x++){
int y=sum-x;
arr[x][y]=value;
// System.out.println(sum+" "+x+" "+y);
value++;
}
}
for(int y=0;y<=num-1;y++){
for(int x=0;x<=num-1-y;x++){
if(x<(num-1-y)) System.out.print(arr[x][y]+" ");
else System.out.println(arr[x][y]);
}
}
}
}
思路
生成数组,当输入4时
可以看到数字是按照1递增的,数字从小到大遍历的索引如下。且输入5是在输入4的基础上增了几个数而已。
(0,0) sum为0
(0,1) (1,0) sum为1
(0,2) (1,1) (2,0) sum为2
(0,3) (1,2) (2,1) (3,0) sum为3
遍历x坐标:每次从0开始,一直到sum,y的坐标为sum-x
打印
一行一行打印即可。打印的坐标:
(0,0) (1,0) (2,0) (3,0)
(0,1) (1,1) (2,1)
(0,2) (1,2)
(0,3)
y的坐标:从0到3
x的坐标对于每一个y:从0到3-y