📖Q1. n의 배수 고르기
정수 n과 정수 배열 numlist가 매개변수로 주어질 때, numlist에서 n의 배수가 아닌 수들을 제거한 배열을 return하도록 solution 함수를 완성해주세요.
✍A1.
class Solution {
public int[] solution(int n, int[] numlist) {
int j=0;
int count=0;
for(int i=0; i<numlist.length;i++){
if(numlist[i]%n==0){
count++;
}
}
int[] answer = new int[count];
for(int i=0; i<numlist.length;i++){
if(numlist[i]%n==0){ //n의 배수 조건
answer[j]=numlist[i];
j++;
}
}
return answer;
}
}
📖Q2. 가위 바위 보
가위는 2 바위는 0 보는 5로 표현합니다. 가위 바위 보를 내는 순서대로 나타낸 문자열 rsp가 매개변수로 주어질 때, rsp에 저장된 가위 바위 보를 모두 이기는 경우를 순서대로 나타낸 문자열을 return하도록 solution 함수를 완성해보세요.
✍A2.
class Solution {
public String solution(String rsp) {
String answer = "";
for(int i=0; i<rsp.length();i++){
char c = rsp.charAt(i);
if(c=='2'){
answer+='0';
}
else if(c=='0'){
answer+='5';
}
else{
answer+='2';
}
}
return answer;
}
}
class Solution {
public String solution(String rsp) {
return Arrays.stream(rsp.split("")).map(s -> s.equals("2") ? "0" : s.equals("0") ? "5" : "2").collect(Collectors.joining());
//Collectors.joining()메소드는 Collectors 입력요소를 단일 문자열로 연결
}
}
📖Q3. 직각삼각형 출력
""의 높이와 너비를 1이라고 했을 때, ""을 이용해 직각 이등변 삼각형을 그리려고합니다. 정수 n 이 주어지면 높이와 너비가 n 인 직각 이등변 삼각형을 출력하도록 코드를 작성해보세요.
✍A3.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=1; i<=n; i++){
System.out.println("*".repeat(i));
//.repeat()함수를 이용하여 출력
}
}
}
📖Q4. 문자열 정리하기(1)
문자열 my_string이 매개변수로 주어질 때, my_string 안에 있는 숫자만 골라 오름차순 정렬한 리스트를 return 하도록 solution 함수를 작성해보세요.
✍A4.
import java.util.*;
class Solution {
public int[] solution(String my_string) {
my_string=my_string.replaceAll("[a-z]",""); //a-z제외 시키기
int[] answer = new int[my_string.length()];
for(int i=0; i<my_string.length();i++){
answer[i]=my_string.charAt(i)-'0';
//char형을 -'0'(48)을 해주면서 int형으로 변환
}
Arrays.sort(answer);
return answer;
}
}
📖Q5. 주사위의 개수
머쓱이는 직육면체 모양의 상자를 하나 가지고 있는데 이 상자에 정육면체 모양의 주사위를 최대한 많이 채우고 싶습니다. 상자의 가로, 세로, 높이가 저장되어있는 배열 box와 주사위 모서리의 길이 정수 n이 매개변수로 주어졌을 때, 상자에 들어갈 수 있는 주사위의 최대 개수를 return 하도록 solution 함수를 완성해주세요.
✍A5.
class Solution {
public int solution(int[] box, int n) {
int answer = (box[0]/n)*(box[1]/n)*(box[2]/n);;
return answer;
}
}
📖Q6. 가장 큰 수 찾기
정수 배열 array가 매개변수로 주어질 때, 가장 큰 수와 그 수의 인덱스를 담은 배열을 return 하도록 solution 함수를 완성해보세요.
✍A6.
class Solution {
public int[] solution(int[] array) {
int[] answer = new int[2];
int max=array[0];
int index=0;
for(int i=0; i<array.length;i++){
if(max<array[i]){
max=array[i];
index=i;
}
}
answer[0]=max;
answer[1]=index;
return answer;
}
}