알고리즘
[백준] - 2438, 2439(서칭) 별찍기
hatch
2023. 2. 11. 16:19
728x90
반응형
* 공부 목표
입출력 - 2557, 1000, 2558, 10950, 10951, 10952, 10953, 11021, 11022, 11718, 11719, 11720, 11721, 2741, 2742, 2739, 1924, 8393, 10818, 2438, 2439, 2440, 2441, 2442, 2445, 2522, 2446, 10991, 10992
- 2438번
문) 첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제
1) Scanner 활용
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
String star = "";
for(int i=0; i<N; i++) {
star += "*";
System.out.println(star);
}
}
}
2) BufferedReader + BufferedWriter 활용 //메모리 훨씬 적고, 시간은 거의 절반 가까이 떨어짐.
import java.io.*;
public class Main{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
String star = "";
for(int i=0; i<N; i++) {
star += "*";
bw.write(star + "\n");
}
br.close();
bw.flush();
bw.close();
}
}
- 2439번(서칭)
문) 첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제
하지만, 오른쪽을 기준으로 정렬한 별(예제 참고)을 출력하시오.
1) 1차 답안
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
String star = "";
for(int i=0; i<N; i++) {
star += "*";
System.out.printf("%5s\n", star);
}
}
}
- 출력 형식을 바꾸면 된다고 생각했음... 실제 결과물도 똑같긴 함.
그러나 출력형식이 잘못되었다고 결과가 뜸.
2) 2차 서칭 답안
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
for(int i=1; i<=N; i++) {
for(int a=1; a<=N-i; a++) {
System.out.print(" ");
}
for(int b=1; b<=i; b++) {
System.out.print("*");
}
System.out.println();
}
}
}
- 별로 이야기할 부분이 없다.
- 1차로 입력횟수만큼 돌리고, 2-1차로 N-i만큼 공백을 채우기 2-2차로 i만큼 "*" 채우기.