[Programmers] #120823 - 직각삼각형 출력하기 [Java][C++][Python]
[Programmers] #120823 - 직각삼각형 출력하기 [Java][C++][Python]
1. 아이디어
*로 높이와 너비가 $n$인 직각 이등변 삼각형을 출력하는 문제다. 위에서부터 $i$번째 줄에 *를 $i$개씩 찍어 $n$줄을 채우면 높이가 $n$이고, 마지막 줄이 $n$개이므로 너비도 $n$이 된다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.io.*;
public class Solution {
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++) {
sb.repeat("*", i).append("\n");
}
System.out.println(sb);
}
}
StringBuilder의 repeat로 *를 i번 반복해 붙였다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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++) {
cout << string(i, '*') << '\n';
}
}
std::string(i, '*')로 '*'를 i개 이어 붙인 문자열을 만들었다.
1
2
3
4
5
6
7
import sys
input = sys.stdin.readline
n = int(input())
for i in range(1, n + 1):
print("*" * i)
문자열에 정수를 곱해 그 횟수만큼 반복했다.
This post is licensed under CC BY 4.0 by the author.