[BaekJoon] #4470 - 줄번호 [Java][C++][Python]
[BaekJoon] #4470 - 줄번호 [Java][C++][Python]
1. 아이디어
입력받은 줄마다 1부터 시작하는 줄 번호와 마침표, 공백을 앞에 붙여 출력하는 문제로, 줄에 공백이 들어 있으므로 단어 단위가 아니라 한 줄 전체를 읽어야 한다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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++) {
sb.append(i).append(". ").append(br.readLine()).append("\n");
}
System.out.println(sb);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
cin.ignore();
for (int i = 1; i <= n; i++) {
string line;
getline(cin, line);
cout << i << ". " << line << '\n';
}
}
cin >> n 뒤에 남은 줄바꿈을 cin.ignore로 버려 첫 std::getline이 빈 줄을 읽지 않게 했다.
1
2
3
4
5
6
7
8
import sys
input = sys.stdin.readline
n = int(input())
for i in range(1, n + 1):
line = input().rstrip()
print(f"{i}. {line}")
This post is licensed under CC BY 4.0 by the author.