프로그래머스
[프로그래머스] 124 나라의 숫자 [C/C++]
치킨먹고싶어요
2022. 6. 23. 17:50
https://programmers.co.kr/learn/courses/30/lessons/12899
코딩테스트 연습 - 124 나라의 숫자
programmers.co.kr
코드
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
string solution(int n) {
string answer = "";
for (int i = 0; pow(3, i) <= n; i++) {
n -= pow(3, i);
if (n % int(pow(3 , i + 1)) < int(pow(3 , i + 1)) / 3) answer += "1";
else if (n % int(pow(3 , i + 1)) < int(pow(3 , i + 1)) / 3 * 2) answer += "2";
else answer += "4";
}
reverse(answer.begin(), answer.end());
return answer;
}
|
cs |
풀이
1. n % (3 ^ 1)을 하였을 때 0이면 가장 뒤의 숫자가 1, 1이면 2, 2이면 4입니다.
2. n % (3 ^ 2)를 하였을 때 0~2이면 그 다음 숫자가 1, 3~5이면 2, 6~8이면 4입니다.
3. n % (3 ^ ?)를 반복하여 줍니다.