TIL_프로그래머스 - Lv0. 옷가게 할인 받기

정윤숙·2023년 6월 9일
0

TIL

목록 보기
164/192
post-thumbnail

📒 오늘의 공부

1. 프로그래머스

Lv0. 옷가게 할인 받기

나의 풀이

const solution=(price)=> {
    let discountedPrice = 0;
    if(price >= 500000){
        discountedPrice = (price*0.80) 
    }
    else if(price >= 300000){
        discountedPrice = price*0.90
    }
    else if(price >= 100000){
        discountedPrice = price*0.95
    }
    else{
            return price
    }
    return Math.trunc(discountedPrice)

}
  • 할인이 적용 되는 최대 금액부터 순서대로!
  • Math.trunc() - 소수점 버린 정수 구하기

다른 풀이

const discounts = [
    [500000, 20],
    [300000, 10],
    [100000,  5],
]

const solution = (price) => {
    for (const discount of discounts)
        if (price >= discount[0])
            return Math.floor(price - price * discount[1] / 100)
    return price
}
  • 반복문 이용
function solution(price) {
    price = price>=500000?price*0.8:price>=300000?price*0.9:price>=100000?price*0.95:price;
    return ~~(price);
}
  • ~~ = double tilde 연산자로 알려진 비트 연산자
    • 소수점 이하를 버리고 정수 부분만 얻을 때 사용
    • 하지만 정수 부분만 얻는 용도로 사용되는 것이 명확하지 않고 가독성을 해칠 수 있기 때문에 Math.trunc() 함수 사용하기
profile
프론트엔드 개발자

0개의 댓글