상세 컨텐츠

본문 제목

[프로그래머스 1단계] 콜라 문제 -c++

알고리즘/프로그래머스 1단계

by 셉인 2024. 2. 24. 09:52

본문

728x90

[프로그래머스 1단계] 콜라 문제 -c++ 

프로그래밍 잘하는 친구가 해주던 말이 생각나는 문제였다.

맨 처음 답안

문제풀이

일단 다 하고 남은 것들을 temp에 넣어서 이 값들을 더해서 다시 해주고 .. 

다시 받은 빈병수 더해주고...

n의 값은 낸 빈병수 + 받은 빈병수 + 남은 빈병수 ...

복잡했다...

#include <string>
#include <vector>
#include <iostream>

using namespace std;

int solution(int a, int b, int n) {
    int answer = 0;
    int temp =0;
    while(n>=a){
        temp += n-((n/a)*a);   
        answer += n/a; 
        n = n/a;
    }
    n+=temp;
    temp =0;
    cout <<n;
    while(n>=a){
        if(n%a==0){
        answer += n/a;
        n =n/a;
        }
        else {
            answer += n/a;
            temp += n-((n/a)*a);
            n = n/a;
        }
    
    }
    return answer;
}

 

채점 결과가 난리났다.

문제풀이

n을 다시 대입시켜주는 것에서 원래의 코드와 많은 차이를 보였다.

받은 빈병 수((n/a)*b) + 남은 빈병수

이렇게 해주다보면 언젠가 n/a가 0이 돼서 while문을 통과하게 된다.

 

답안 1

#include <string>
#include <vector>

using namespace std;

int solution(int a, int b, int n) {
    int answer = 0;
    while(n>=a){
        answer+=((n/a)*b);
        n=n%a+(n/a)*b;
    }
    return answer;
}

답안 2 (프로그래머스 답안)

#include <string>
#include <vector>

using namespace std;

int solution(int a, int b, int n) {
    int answer = 0;
    while(n >= a){
        answer += b;
        n -= (a - b);
    }
    return answer;
}

 

답안 2를 보고 이렇게 간단하게 적을 수 있구나 생각이 들어서 충격적이었다.

그냥 2병주고 1병 받는것을 계속 반복한 것 같다.

 

[프로그래머스/1단계] 콜라 문제 -c++ 

정답률 69%

728x90

관련글 더보기

댓글 영역