我该怎么做:
*******
-*****-
--***--
---*---
--***--
-*****-
*******
Run Code Online (Sandbox Code Playgroud)
以下是我为完成上述操作而编写的代码,但它没有按预期工作:
public static void stars(/*int jmlBaris*/) {
for ( int i = 7; i >= 1; i-=2) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
for (int i = 1; i <= 7; i+=2) {
for (int j = 1; j <= i; j++){
System.out.print("*");
}
System.out.println("");
}
}
public static void main(String[] args) {
stars();
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我写它的方式.
// three loops
public static void stars(int size) {
for (int y = 0; y < size; y++) {
for (int i = 0; i < y && i < size - y - 1; i++)
System.out.print(' ');
for (int i = Math.min(y, size - y - 1); i < Math.max(y + 1, size - y); i++)
System.out.print('*');
System.out.println();
}
}
Run Code Online (Sandbox Code Playgroud)
要么
// two loops
public static void stars(int size) {
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++)
System.out.print(
(x >= y && x < size - y) ||
(x >= size - y - 1 && x <= y) ? '*' : ' ');
System.out.println();
}
}
Run Code Online (Sandbox Code Playgroud)
要么
// one loop
public static void stars(int size) {
for (int i = 0; i < size * size; i++) {
int y = i / size, x = i % size;
System.out.print(
(x >= y && x < size - y) ||
(x >= size - y - 1 && x <= y) ? '*' : ' ');
if (x == size - 1)
System.out.println();
}
}
Run Code Online (Sandbox Code Playgroud)
注意:无论是使用一个,两个还是三个循环,时间复杂度为O(N ^ 2).确定这一点的一个简单方法是,无论如何完成,产生的恒星数量为O(N ^ 2).