728x90
level 2 : 123 나라의 숫자
https://programmers.co.kr/learn/courses/30/lessons/12899?language=cpp
코딩테스트 연습 - 124 나라의 숫자
programmers.co.kr
코드
//프로그래머스 124나라의 숫자
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string solution(int n) {
string answer = "";
while (n) {
n--;
if (n % 3 == 0) {
answer = "1" + answer;
}
else if (n % 3 == 1) {
answer = "2" + answer;
}
else {
answer = "4" + answer;
}
n /= 3;
}
return answer;
}
int main() {
int n = 9;
cout << solution(n) << "\n";
return 0;
}
설명
0,1,2로 이루어진 3진법과 비슷하다.
하지만 3진법은 0부터 시작 이 문제는 1부터 시작이다. 따라서 -1씩 해주도록한다.
고찰
다른 사람의 풀이를 봤을 때 신기한 코드가 있었다.
"412"[0]; //string
다음과 같이 string을 사용할 수 있었다.
"412"와 같은 string에서 배열처럼 index를 입력하여 출력해도 된다.
string에서 배열같이 사용해도 된다는 것은 알았지만 다음과 같이 사용 가능한지는 처음 알게 되었다.
728x90
'알고리즘 > 프로그래머스' 카테고리의 다른 글
알고리즘(c++) / 프로그래머스 level 3 : 네트워크 (0) | 2021.08.02 |
---|---|
알고리즘(C++) / 프로그래머스 level 3 : 단어 변환 (0) | 2021.08.01 |
알고리즘(C++) / 프로그래머스 level 2 : 짝지어 제거하기 (0) | 2021.07.26 |
알고리즘(C++) / 프로그래머스 level 2 : 기능 개발 (0) | 2021.07.25 |
알고리즘(C++) / 프로그래머스 level 2 : 멀쩡한 사각형 (0) | 2021.07.24 |
댓글