머쓱이네 옷가게는 10만 원 이상 사면 5%, 30만 원 이상 사면 10%, 50만 원 이상 사면 20%를 할인해줍니다.구매한 옷의 가격 price가 주어질 때, 지불해야 할 금액을 return 하도록 solution 함수를 완성해보세요.
<생각과정>
if else if문으로 냅다 나열해주는 조건문이지 않나...
하고 코딩했는데
class Solution {
public int solution(int price) {
int answer = 0;
if (price >= 100000){
answer = (0.95 * price);
}
else if (price>=300000){
answer = (0.9 * price);
}
else if (price>=500000){
answer = (0.8 * price);
}
return answer;
}
}
에러가났다 왜일까 생각하니 이거 type 안맞춰놨다...
class Solution {
public int solution(int price) {
int answer = 0;
if (price >= 100000){
answer = (int)(0.95 * price);
}
else if (price>=300000){
answer = (int)(0.9 * price);
}
else if (price>=500000){
answer = (int)(0.8 * price);
}
return answer;
}
}

다시 떠버린 에러...?
엥 0.8 * price 했는데 왜 551000이 나왔지

...?
뭘 놓친걸까
근데 생각해보니 else if 써줄때 항상 내림차순으로 썼던거같은데 라는 생각에
class Solution {
public int solution(int price) {
int answer = 0;
if (price >= 500000){
answer = (int)(0.80 * price);
}
else if (price>=300000){
answer = (int)(0.9 * price);
}
else if (price>=100000){
answer = (int)(0.95 * price);
}
return answer;
}
}

여전히 띠용이다 ... 간과한거 하나가 있네
10만원 이하는 할인이 없네
class Solution {
public int solution(int price) {
int answer = 0;
if (price >= 500000){
answer = (int)(0.80 * price);
}
else if (price>=300000){
answer = (int)(0.9 * price);
}
else if (price>=100000){
answer = (int)(0.95 * price);
}
else if (price < 100000){
answer = (int) price;
}
return (int)answer;
}
}

그럼 else if가 내림차순이 아닌 오름차순이였어도 가능 했던거 아닐까?
class Solution {
public int solution(int price) {
int answer = 0;
if (price < 100000){
answer = (int) price;
}
else if (price >= 100000){
answer = (int)(0.95 * price);
}
else if (price>=300000){
answer = (int)(0.9 * price);
}
else if (price>=500000){
answer = (int)(0.80 * price);
}
return (int)answer;
}
}

왜이러시는건데요 진짜
아니 그리고 else if 는 독립적으로 작동하는데 오름차순 내림차순이 의미가 뭐가 있나... 다시 작성...
class Solution {
public int solution(int price) {
int answer = 0;
if (price >= 500000){
answer = (int)(0.80 * price);
}
else if (price>=300000){
answer = (int)(0.9 * price);
}
else if (price>=100000){
answer = (int)(0.95 * price);
}
else {
answer = (int)(price);
}
return answer;
}
}
여기서도 마찬가지로 그냥 10만원 이하에 대한 값을 생략했던 거다 그냥... else if 잘쓰자...

'코딩테스트 > 프로그래머스_코딩 기초 트레이닝' 카테고리의 다른 글
[프로그래머스] 조건에 맞게 수열 변환하기 3 (2) | 2023.05.30 |
---|---|
[프로그래머스] 첫 번째로 나오는 음수 (2) | 2023.05.29 |
[프로그래머스] 아이스 아메리카노 (0) | 2023.05.26 |
[프로그래머스] 문자열을 정수로 변환하기 (0) | 2023.05.26 |
[프로그래머스] 문자열로 변환 (0) | 2023.05.26 |