1027 打印沙漏 (20 point(s))
题目描述
本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印
*****
***
*
***
*****
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。
输入格式
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。
输出格式
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。
输入样例1
19 *
输出样例1
*****
***
*
***
*****
2
输入样例2
17 #
输出样例2
#####
###
#
###
#####
0
代码????
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] data = sc.nextLine().split(" ");
int n = Integer.parseInt(data[0]);
char ch = data[1].charAt(0);
sc.close();
int layerNum = 1;
int outLayers = 6;
int left = n - 1;
while (left >= outLayers) {
layerNum += 2;
left -= outLayers;
outLayers += 4;
}
int spaceNum = 0;
int oneLayer = (outLayers - 4) / 2;
for (int i = 0; i <= layerNum / 2; ++i) {
for (int j = spaceNum; j > 0; --j) {
System.out.print(" ");
}
for (int j = oneLayer; j > 0; --j) {
System.out.print(ch);
}
System.out.println();
++spaceNum;
oneLayer -= 2;
}
spaceNum -= 2;
oneLayer += 4;
for (int i = layerNum / 2 + 1; i < layerNum; ++i) {
for (int j = spaceNum; j > 0; --j) {
System.out.print(" ");
}
for (int j = oneLayer; j > 0; --j) {
System.out.print(ch);
}
System.out.println();
--spaceNum;
oneLayer += 2;
}
System.out.println(left);
}
}
版权声明
- 转载、参考、引用必须在首页添加如下文字:
[PAT(A) 1027 打印沙漏(Java)—wowpH](https://blog.csdn.net/pfdvnah/article/details/95763096)
- 代码原创,公开引用不能删除首行注释(作者,版本号,时间等信息);
- 如果有疑问欢迎评论区留言,尽量解答;
- 如果有错误,还望大侠评论区指正。