Algorithms

Programmers Day 5

유영서 2023. 7. 11. 23:29

- 옷가게 할인 받기

10만 원 이상 사면 5%, 30만 원 이상 사면 10%, 50만 원 이상 사면 20%를 할인하여 가격 return

 

 

내가 쓴 코드

class Solution {
    public int solution(int price) {
        if (10 <= price && price <= 1000000){
            if (price >= 100000 && price < 300000) price *= 0.95;
            else if (price >= 300000 && price < 500000) price *= 0.9;
            else if (price >= 500000) price *= 0.8;
        }
        return price;
    }
}

 

아 다른 사람이 쓴 코드도 비슷한데 저 if문 조건 쓸 때 50만원 이상부터 써 줬다. 그러면 정말 문제대로 ~이상만 조건에 써줘도 되는데! 다음부터는 그렇게 해야지 큰 순서대로!!

 

 

- 아이스 아메리카노

 한잔에 5,500원인데 가진 돈으로 최대 몇잔 마실 수 있는지 그리고 남는 돈까지 return

 

 

내가 쓴 코드

class Solution {
    public int[] solution(int money) {
        int[] answer = new int[2];
        int num = 0; int rest = 0;
        num = money / 5500; answer[0] = num;
        rest = money % 5500; answer[1] = rest;
        return answer;
    }
}

 

다른사람이 쓴 코드

class Solution {
    public int[] solution(int money) {
        return new int[] { money / 5500, money % 5500 };
    }
}

아예 배열 만들때 원소 넣어줄수 있으니까... 그때! 대박

 

 

 

- 나이 출력

age가 주어질 때, 2022년을 기준 출생 연도를 return

아니 근데 갑자기 문제 난이도가 확 떨어졌다

 

내가 쓴 코드

class Solution {
    public int solution(int age) {
        int answer = 0;
        if (age > 0 && age <= 120){
            answer = 2022-age+1;
        }
        return answer;
    }
}

 

다른 사람이 쓴 코드

import java.time.*;
class Solution {
    public int solution(int age) {
        LocalDate today = LocalDate.now();
        return today.getYear() - age + 1;
    }
}

대박! 시간을 가져왔어 대박

오늘 날짜 가져와서 거기서 년도수를 추출해서 하다니 똑똑한 코드다 

 

 

- 배열 뒤집기

 

사실 처음에는 Collections의 reverse 함수를 쓰려했는데

List<int[]> list = Arrays.asList(num_list);      
Collections.reverse(list);       
int[] reverseArr = list.toArray(num_list);

자꾸 에러가 났다..

/Solution.java:8: error: no suitable method found for toArray(int[])
int[] reverseArr = list.toArray(num_list);
^
method Collection.<T#1>toArray(IntFunction<T#1[]>) is not applicable
(cannot infer type-variable(s) T#1
(argument mismatch; int[] cannot be converted to IntFunction<T#1[]>))

 

어쩌구...저쩌구...

 

그래서 반복문으로 해결하기로 결정

 

import java.util.*;
class Solution {
    public int[] solution(int[] num_list) {
        int[] reverse_list = new int[num_list.length];

        for (int i=0; i<num_list.length; i++){
            reverse_list[i] = num_list[num_list.length-i-1];
        }

        return reverse_list;
    }
}

 

 

다른 사람들은

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;

class Solution {
    public int[] solution(int[] numList) {
        List<Integer> list = Arrays.stream(numList).boxed().collect(Collectors.toList());

        Collections.reverse(list);
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}

우아 이게 뭐지

진짜 Stream 공부해야겠다