[#29][알고리즘] 124나라의 숫자

프로그래머스 > 124나라의 숫자

문제 링크(https://programmers.co.kr/learn/challenge_codes/158)























C++풀이
#include<iostream>
#include<vector>
#include<algorithm>    //reverse()사용 위해서
using namespace std;
string change124(int no)
{
  string answer = "";
  int rest, quo;
  
  while(no > 0){
    rest = no % 3;  //나머지
    quo = no / 3;   //몫
    
    if( rest == 0 ) { //나머지가 0이면
      answer.append("4"); //4 append. 3으로 나누어 떨어지는 수는 마지막 수가 4이므로
      quo--//몫--
      if(quo == 0break//몫이 0이되면 break
      else no = quo; //몫이 0이 아닌 경우 no에 몫을 넣어줌. no가 15인 경우 -> no = 4
      continue;
    }
    
    no = quo;
    answer.append(to_string(rest));
  }
  
  // string 거꾸로
  reverse(answer.begin(), answer.end());
  return answer;
}
int main()
{
    int testNo = 15;
    string testAnswer = change124(testNo);
    cout<<testAnswer;
}
cs
--------------------------------------------------
no = 15

rest = 15 % 3 = 0
quo = 15 / 3 = 5

if문 조건 만족 : rest == 0
 answer = "4"
 quo = 4
 no = 4
--------------------------------------------------
no = 4

rest = 4 % 3 = 1
quo = 4 / 3 = 1

if문 조건 만족x
 no = 1
 answer = "41"
---------------------------------------------------
no = 1

rest = 1 % 3 = 1
quo = 1 / 3 = 0

if문 조건 만족x
 no = 0
 answer = "411"

---------------------------------------------------
no = 0 => while문 종료
reverse 후 answer = "114"





다른사람 풀이(완전신기)
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
 
string change124(int no){
    string answer = "";
    int rest;
 
    while (no > 0) {
        rest = no % 3;
        no = no / 3;
        if (rest == 0)
            no--;
        answer += "412"[rest];
    }
    reverse(answer.begin(), answer.end());
    return answer;
}
 
int main(){
    int testNo = 10;
    string testAnswer = change124(testNo);
    cout << testAnswer;
}
cs

댓글

가장 많이 본 글