[자바JAVA]1072 : [기초-반복실행구조] 정수 입력받아 계속 출력하기

문제 1072 : [기초-반복실행구조] 정수 입력받아 계속 출력하기

n개의 정수가 순서대로 입력된다.(-2147483648 부터 +2147483647까지, 단 n의 최대 개수는 알 수 없다.)
n개의 입력된 정수를 순서대로 출력해보자.
while( ), for( ), do~while( ) 등의 반복문을 사용할 수 없다.

문제 힌트를 보면 C언어의 lable과 goto를 사용하라고 나왔다.
goto는 자바에 있는 예약어지만 기능은 없다.

  • 입력예시
    첫 줄에 정수의 개수 n이 입력되고,
    두 번째 줄에 n개의 정수가 공백을 두고 입력된다. (-2147483648 부터 +2147483647까지, 단 n의 최대 개수는 알 수 없다.)
1
2
5
1 2 3 4 5
  • 출력예시
    n개의 정수를 한 개씩 줄을 바꿔 출력한다.
1
2
3
4
5
1
2
3
4
5




풀이1

  • 메모리: 15004 시간: 114
1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) throws IOException {
//sol1 메모리: 15004 시간: 114
Scanner sc = new Scanner(System.in);

int len = sc.nextInt();
int[] value = new int[len];

for(int i = 0; i <value.length; i++) {
value[i] =sc.nextInt();
System.out.println(value[i]);
}
}




풀이2

  • 메모리: 14316 kb 수행 시간: 111 ms
1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) throws IOException {
// sol2
// 메모리: 14316 kb 수행 시간: 111 ms
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int[] nums = new int[len];

for(int i : nums){
nums[i] = sc.nextInt();
System.out.println(nums[i]);
}
sc.close();
}




풀이3

  • 메모리 :11132 kb 수행 시간:68 ms
1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) throws IOException {
//sol3
// 메모리 :11132 kb 수행 시간:68 ms
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String n = br.readLine();
String[] num = br.readLine().split(" ");
for(String s : num){
System.out.println(s);
}
}




배운지식

입력을 두 번 받으면 되는 문제였다.
난 어떻게든 한 번 입력받고 처리할려고했으니 잘 될 턱이 있나…
역시 BufferedReader가 빠르다




다른 문제 풀이가 보고싶다면?

Comments