■ 题目描述
小华是个很有对数字很敏感的小朋友,他觉得数字的不同排列方式有特殊美感。
某天,小华突发奇想,如果数字多行排列,第一行1个数,第二行2个,第三行3个,即第n行有n个数字,并且奇数行正序排列,偶数行逆序排列,数字依次累加。
这样排列的数字一定很有意思。聪明的你能编写代码帮助小华完成这个想法吗?
规则总结如下:
a、每个数字占据4个位置,不足四位用‘’补位,如1打印为1**。
b、数字之间相邻4空格。
c、数字的打印顺序按照正序逆序交替打印,奇数行正序,偶数行逆序。
d、最后一行数字顶格,第n-1行相对第n行缩进四个空格
输入描述
第一行输入为N,表示打印多少行; 1<=N<=30
输入:2
输出描述
XXXX1***
3XXXX2
示例1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
2
输出
1***
3*** 2***
备注
符号*表示,数字不满4位时的补位,符号X表示数字之间的空格。注意实际编码时不需要打印X,直接打印空格即可。此处为说明题意,故此加上X。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class NumberReversePrint {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<List<String>> lists = new ArrayList<>();
for (int i = 1; i <= n; i++) {
List<String> list = new ArrayList<>();
int fn = firstNum(i);
lists.forEach(x -> {
x.add(0, " ");
});
for (int j = 0; j < i; j++) {
String temp = fn++ + "***";
list.add(temp.substring(0, 4));
if (j != i - 1) {
list.add(" ");
}
}
if ((i) % 2 == 0) {
Collections.reverse(list);
}
lists.add(list);
}
lists.forEach(x -> {
StringBuilder res = new StringBuilder();
for (String s : x) {
res.append(s);
}
System.out.println(res);
});
}
public static int firstNum(int n) {
if (n == 1) {
return 1;
}
return firstNum(n - 1) + n - 1;
}
}
#include<bits/stdc++.h>
using namespace std;
void print_int(int num)
{
if (num / 10 == 0) {
cout << num << "***" << " ";
} else if (num / 10 == 1) {
cout << num << "**" << " ";
} else if (num / 10 == 2) {
cout << num << "*" << " ";
} else if (num / 10 == 3) {
cout << num << " ";
} else {
cout << "too long" << " ";
}
}
void print_reverse(int start, int end, int flag)
{
if (flag == 1) {
//正序打印
for (int i = start; i<= end; i++) {
print_int(i);
}
} else {
for (int i = end; i >= start; i--) {
print_int(i);
}
}
}
int main()
{
int N;
cin >> N;
int i = 1;
int start = 1;
int end = 1;
while (i <= N) {
print_reverse(start, end, i % 2);
//记得换行
cout << endl;
i += 1;
start = end + 1;
end = end + i;
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(int n)
{
int blanknum = 0;
int num = 1;
for(int i = 1; i <= n; ++i) {
blanknum = (n-i);
while(blanknum-- > 0) {
cout << "----";
}
int numend = num + i;
if(i%2 == 1) {
while(num < numend) {
cout << left << setw(4) << num;
++num;
}
} else {
int numstart = num;
num = numend;
while(--numend >= numstart) {
cout << left << setw(4) << numend;
}
}
cout << endl;
}
}
};
int main()
{
Solution obj;
obj.solve(15);
}