알고리즘/백준
[백준] 10807 - 개수 세기
leegeonwoo
2023. 10. 24. 22:07
• 문제
배열을 이용하여 해당 배열에 값을 넣어 특정 값이 몇 개인지 개수를 출력하는 프로그램이다.
• 풀이
입력
- 배열에 들어갈 숫자의 개수인 N
- 배열의 인덱스에 들어갈 값
- 개수를 알기위한 입력 값 V
배열의 길이는 입력받은 N으로 설정해주고,
배열의 입력은 for문을 이용하여 값을 입력받는다.
int[] arr = new int[N];
for(int i=0; i<arr.length; i++) {
arr[i] = sc.nextInt();
}
v값이 몇 번 나오는지 체크하기 위한 count변수를 생성해주고
each for문을 사용하여 v값과 배열의 인덱스 값이 같으면 count를 ++해준다.
int count = 0;
for(int tmp : arr) {
if(tmp == v) {
count++;
}
}
Scanner와 System.out.pritnln()을 사용한 전체코드
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr = new int[N];
for(int i=0; i<arr.length; i++) {
arr[i] = sc.nextInt();
}
int v = sc.nextInt();
int count = 0;
for(int tmp : arr) {
if(tmp == v) {
count++;
}
}
System.out.println(count);
}
}
BufferedReader와 BufferedWriter를 사용한 전체코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
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());
int arr[] = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine()," ");
for(int i=0; i<arr.length; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
int V = Integer.parseInt(br.readLine());
int count = 0;
for(int tmp : arr) {
if(V == tmp) {
count++;
}
}
bw.write(count + "\n");
bw.flush();
bw.close();
}
}
728x90