프로그래머스 코딩테스트(직각삼각형 출력하기, n의 배수 고르기, 최댓값 만들기 (2))
<직각삼각형 출력하기>
문제 설명
"*"의 높이와 너비를 1이라고 했을 때, "*"을 이용해 직각 이등변 삼각형을 그리려고합니다. 정수 n 이 주어지면 높이와 너비가 n 인 직각 이등변 삼각형을 출력하도록 코드를 작성해보세요.
풀이
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=0;i<n;i++){
for(int j=0;j<=i;j++){
System.out.print("*");
}
System.out.println();
}
}
}
다른 사람 풀이
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));
}
}
}
<n의 배수 고르기>
문제 설명
정수 n과 정수 배열 numlist가 매개변수로 주어질 때, numlist에서 n의 배수가 아닌 수들을 제거한 배열을 return하도록 solution 함수를 완성해주세요.
풀이
class Solution {
public int[] solution(int n, int[] numlist) {
int num = 0;
String str = "";
for(int i:numlist){
if(i%n==0){
str+=i+",";
num++;
}
}
String[] arr = str.split(",");
int[] answer = new int[num];
for(int j=0;j<answer.length;j++){
answer[j] = Integer.parseInt(arr[j]);
}
return answer;
}
}
다른 사람 풀이
class Solution {
public int[] solution(int n, int[] numlist) {
int count = 0;
for(int i : numlist){
if(i%n==0){
count++;
}
}
int[] answer = new int[count];
int idx = 0;
for(int i : numlist){
if(i%n==0){
answer[idx]=i;
idx++;
}
}
return answer;
}
}
<최댓값 만들기 (2)>
문제 설명
정수 배열 numbers가 매개변수로 주어집니다. numbers의 원소 중 두 개를 곱해 만들 수 있는 최댓값을 return하도록 solution 함수를 완성해주세요.
풀이
import java.util.Arrays;
class Solution {
public int solution(int[] numbers) {
Arrays.sort(numbers);
return numbers[0]*numbers[1]>=numbers[numbers.length-1]*numbers[numbers.length-2]?numbers[0]*numbers[1]:numbers[numbers.length-1]*numbers[numbers.length-2];
}
}
다른 사람 풀이
import java.util.*;
class Solution {
public int solution(int[] numbers) {
int len = numbers.length;
Arrays.sort(numbers);
return Math.max(numbers[0] * numbers[1], numbers[len - 2] * numbers[len - 1]);
}
}