문제 풀이

[백준] 10871번: X보다 작은 수 - JAVA (자바)

auyeol 2023. 2. 10. 23:44
728x90

 

 

문제

https://www.acmicpc.net/problem/10871

 

10871번: X보다 작은 수

첫째 줄에 N과 X가 주어진다. (1 ≤ N, X ≤ 10,000) 둘째 줄에 수열 A를 이루는 정수 N개가 주어진다. 주어지는 정수는 모두 1보다 크거나 같고, 10,000보다 작거나 같은 정수이다.

www.acmicpc.net

 

첫번째 줄에 정수 개수 N과 정수 X를 선언한 다음, 두번째 줄에 N개의 정수를 입력한다.

 

이후, X보다 작은 수들을 출력하면 되는 문제이다.

 

입력                                    출력
5 3                                     1 2  
1 3 2 8 5

 

------------------------------------------------------------------------------------------------------------------

 

 

풀이

 

(1) Scanner 사용 

 

 

 

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt(); // 정수의 개수 n 입력받기
		int x = sc.nextInt(); // 정수 X
		
		int array1[] = new int[n];
		
		for(int i=0;i<array1.length;i++) {
			array1[i] = sc.nextInt();
		}
		
		sc.close();
		
		for(int i=0;i<array1.length;i++) {
			if(array1[i]<x) // x보다 작은 경우
				System.out.print(array1[i] + " "); // 출력
		}
		
	}
}

 

------------------------------------------------------------------------------------------------------------------

 

 

(2) BufferdReader 사용 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;


public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer strtk = new StringTokenizer(br.readLine()," ");
	    
		int n = Integer.parseInt(strtk.nextToken());
		int x = Integer.parseInt(strtk.nextToken());
		
		strtk = new StringTokenizer(br.readLine()," "); // 두 번째 줄 입력을 위해 다시 선언
		
		for(int i=0;i<n;i++) {
        	int ans = Integer.parseInt(strtk.nextToken());	
        	
        	if(ans<x) System.out.print(ans+" ");
        }
                
	}
}

 

입력할 때 2줄을 연속해서 입력해야 하기 때문에 한번 다시 선언해주었다.

 

728x90