PS/BaekJoon
[2522] 별 찍기-12 : Java
eee_269
2021. 4. 14. 01:20
728x90
반응형
2522번: 별 찍기 - 12
첫째 줄부터 2×N-1번째 줄까지 차례대로 별을 출력한다.
www.acmicpc.net
문제분석
1. 2중 for문으로 출력하기
: 공백 출력 for문, 별 출력 for문 -> 한 줄에 3번의 for문 수행
2. String 입력을 통해 단순반복 입력 가능
: new String(new char[반복할 숫자]).replace('\u0000', '출력할 문자');
- new String을 통해 새로운 String만들고
- new char[]를 통해 문자 배열을 문자열로 넣어주기
- 그 문자 배열의 크기는 반복할 숫자이고, 안에 들어있는 내용은 char의 null값인 \u0000 일 것이다.
- replace를 통해 우리가 출력하고자하는 공백이나 별로 \u0000을 바꿔준다.
1과 2의 차이점: 문제 해결 시간 단축
차례대로 1번 형식으로 한 문제 해결의 시간이 488ms이고, 2번 형식으로 한 것은 264ms인 것을 알 수 있다.
Java
1번 형식 - 2중 for문
import java.util.*;
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=1; i<2*n; i++) {
if(i == n) {
for(int j=0; j<i; j++) {
System.out.print('*');
}
} else if (i < n) {
for(int j=0; j<n-i; j++) {
System.out.print(' ');
}
for(int j=0; j<i; j++) {
System.out.print('*');
}
} else {
for(int j=0; j<i-n; j++) {
System.out.print(' ');
}
for(int j=0; j<2*n-i; j++) {
System.out.print('*');
}
}
System.out.println();
}
}
}
2번 형식 - String으로 출력할 문자열 입력
import java.util.*;
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=1; i<2*n; i++) {
String s = "";
if(i == n) {
s = new String(new char[n]).replace('\u0000', '*');
} else if (i < n) {
s = new String(new char[n-i]).replace('\u0000', ' ');
s += new String(new char[i]).replace('\u0000', '*');
} else {
int j = 2*n-i;
s = new String(new char[n-j]).replace('\u0000', ' ');
s += new String(new char[j]).replace('\u0000', '*');
}
System.out.println(s);
}
}
}
728x90
반응형