[BaekJoon] #10992 - 별 찍기 - 17 [Java][C++][Python]
[BaekJoon] #10992 - 별 찍기 - 17 [Java][C++][Python]
1. 아이디어
가운데 정렬 삼각형에서 왼쪽 변과 오른쪽 변을 별로 찍고 마지막 줄은 별 $2N - 1$개로 채워 밑변을 닫는다. 마지막 줄을 뺀 위에서부터 $i$번째 줄은 앞 공백 $N - i$개 뒤에 길이 $2i - 1$인 구간이 오고, 이 구간의 첫 칸과 마지막 칸이 별이며 그 사이는 공백이다. $N$이 1이면 첫 줄이 곧 마지막 줄이라 별 하나만 찍힌다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(br.readLine());
for (int i = 1; i < n; i++) {
for (int j = 1; j <= n - i; j++) {
sb.append(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
if (j == 1 || j == 2 * i - 1) {
sb.append("*");
} else {
sb.append(" ");
}
}
sb.append("\n");
}
for (int j = 1; j <= 2 * n - 1; j++) {
sb.append("*");
}
System.out.println(sb);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 1; i < n; i++) {
for (int j = 1; j <= n - i; j++) {
cout << ' ';
}
for (int j = 1; j <= 2 * i - 1; j++) {
if (j == 1 || j == 2 * i - 1) {
cout << '*';
} else {
cout << ' ';
}
}
cout << '\n';
}
for (int j = 1; j <= 2 * n - 1; j++) {
cout << '*';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import sys
input = sys.stdin.readline
n = int(input())
out = []
for i in range(1, n):
line = " " * (n - i)
for j in range(1, 2 * i):
if j == 1 or j == 2 * i - 1:
line += "*"
else:
line += " "
out.append(line)
out.append("*" * (2 * n - 1))
print("\n".join(out))
This post is licensed under CC BY 4.0 by the author.