Algorithm/C++ - 프로그래머스
프로그래머스 Level2 - 124 나라의 숫자 C++
ㅇㅇ잉
2021. 3. 20. 01:22
1. 배열 사용하지 않고 풀기
진법문제는 대부분 나머지로 계산해서 접근할 수 있다.
아래 조건에서 볼 수 있다시피, 각각 3으로 나눠 나머지에 따라 answer에 추가시켜준다.
이때 뒤로 추가시키지 않는거 주의!
앞으로 추가시켜줘야한다.
만약 3으로 나눠졌을때는 -1를 해주는 것도 잊지 말자
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#include <string>
#include <vector>
#include <iostream>
using namespace std;
string solution(int n) {
string answer = "";
while(n!=0){
if(n%3==1){
answer = '1'+answer;
}else if(n%3==2){
answer = '2'+answer;
}
else if(n%3==0){
answer = '4'+answer;
--n;
}
n/=3;
}
return answer;
}
|
cs |
2. 배열 사용하기 + 코드 정리
한번 더 코드를 정리해서 풀어봤다.
배열의 index를 이용해서 풀어보자
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <string>
#include <vector>
using namespace std;
string solution(int n) {
string answer = "";
string arr[3] ={"4","1","2"};
while(n){
answer = arr[n%3]+answer;
if(n%3) { n/=3; }
else { n/=3; --n;}
}
return answer;
}
|
cs |