오늘의 취준/오늘의 코테

[JAVA] 알고리즘 문제풀이 입문 2.05, 2.06번

gogoem 2023. 5. 23. 12:45
728x90

강의: https://inf.run/w779

 

자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비 - 인프런 | 강의

자바(Java)로 코딩테스트를 준비하시는 분을 위한 강좌입니다. 코딩테스트에서 가장 많이 출제되는 Top 10 Topic을 다루고 있습니다. 주제와 연동하여 기초문제부터 중급문제까지 단계적으로 구성

www.inflearn.com

 

2.05번

import java.util.Scanner;
 
public class Main {

  public void solution(int n){
    int[] array = new int[n];
    int answer = 0;

    for(int i = 2; i < n; i++){
      if(array[i] == 0) answer++;
      for(int j = i; j < n; j+=i) array[j] = 1;
    }
    System.out.print(answer);
  }

  public static void main(String[] args){
    Main m = new Main();
    Scanner in = new Scanner(System.in);
    int num = in.nextInt();
    in.close();

    m.solution(num);
  }
}
 

 

 

2.06번

import java.util.ArrayList;
import java.util.Scanner;
 
public class Main {

  public boolean isPrime(int x){
    if(x == 1) return false;
   
    int i = 2;
    while(i < x){
      if(x%i == 0){
        return false;
      }
      i++;
    }
    return true;
  }

  public void solution(int n, int[] arr){
    ArrayList<Integer> answer = new ArrayList<>();
    for(int i = 0; i < n; i++){
      int tmp = arr[i];
      int t = 0;
      int res = 0;
      while(tmp !=0){
        t = tmp % 10;
        res = res * 10 + t;
        tmp = tmp/10;
      }
      arr[i] = res;
      if(isPrime(res)){
        answer.add(res);
      }
    }
    for(int x : answer){
      System.out.print(x + " ");
    }
  }

  public static void main(String[] args){
    Main m = new Main();
    Scanner in = new Scanner(System.in);
    int num = in.nextInt();
    int[] arr = new int[num];
    for(int i = 0; i < num; i++){
      arr[i] = in.nextInt();
    }
    in.close();

    m.solution(num, arr);
  }
}