團隊天梯賽-------(2)分值:20java
題目要求:你寫個程序把給定的符號打印成沙漏的形狀。例如給定17個「*」,要求按下列格式打印
*****
***
*
***
*****
所謂「沙漏形狀」,是指每行輸出奇數個符號;各行符號中心對齊;相鄰兩行符號數差2;符號數先從大到小順序遞減到1,再從小到大順序遞增;首尾符號數相等。
給定任意N個符號,不必定能正好組成一個沙漏。要求打印出的沙漏能用掉儘量多的符號。input
解題思路:運用分治思想將此沙漏看作上下兩部分,合理利用循環對此提進行解答。class
代碼以下;import
import java.util.*;
public class pta_2 {
public static void pic(int q,String w) {
final int SIZE = 1000;
int[] a = new int[SIZE];
int[] b = new int[SIZE];
int i = 0,j = 1,k = 0;
int temp = 0,l = 0,temp1 = 0,temp2 = 1,temp3 = 0;
int n = 0,f = 0;
for(i = 0;i<SIZE; i++) {
a[i] = j;
j+=2;
}
b[0] = 1;
for(i = 1;i<SIZE; i++) {
b[i] = b[i-1] + 2 * a[i];
}
for(i = 0; i < SIZE;i++) {
if(q > b[i] && q < b[i+1]) {
temp2 = i;
break;
}
else if(q == b[i]) {
temp2 = i;
break;
}
}
temp = a[temp2];
temp1 = temp;
for(i = 0; i < temp; i++) {
if(i < temp / 2){
for(k = 0; k < (temp - temp1) / 2;k++) {
System.out.printf("%1s"," ");
}
for(l = 0; l < temp1;l++) {
System.out.print(w);
}
temp1-=2;
System.out.println();
}
else{
for(f = 0; f < ((temp - temp1) / 2);f++) {
System.out.printf("%1s"," ");
}
for(n = 0;n < temp1;n++) {
System.out.print(w);
}
temp1+=2;
System.out.println();
}
}
System.out.print(q - b[temp2]);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int count = input.nextInt();
String fuhao = input.next();
pic(count,fuhao);
input.close();
}
}循環