본문 바로가기
IT/Algorithm

재귀 - 2진수 변환

by 신인용 2020. 9. 28.
반응형

 

재귀 - 2진수 변환

 

 

 

문제 출저 - 코드업 codeup.kr/problem.php?id=1920

 

 

 

 

풀이 생각

1. 2진수로 표현한다.

 => 결국 2로 나누는 연산과 관련 있을 것임

 => 2로 나눈 나머지가 1이면 1, 0이면 0을 붙여나가주자

2. 출력값을 역순으로 해주어야 함

 => 스택으로 구현

 

* 그런데 이 문제에서 for문 사용이 불가해 채점이 불가했음

 => 스택말고 string으로 구현하고, 역순으로 만들어주고 출력해주자

 

 

my code (stack)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
 
using namespace std;
 
vector<char> binary;
 
void func(int n) {
    if (n <= 0return;
 
    int res = n % 2;
    if (res == 1) binary.push_back('1');
    else binary.push_back('0');
 
    func(n / 2);
}
 
int main(void) {
    cin.sync_with_stdio(false);
 
    int n;
    cin >> n;
 
    func(n);
 
    if (binary.empty()) binary.push_back('0');
 
    size_t size = binary.size();
    for (size_t i = 0; i < size++i) {
        cout << binary.back();
        binary.pop_back();
    }
}
cs

 

 

my code (string)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
int cnt = 0;
char binary[101];
 
void func(int n) {
    if (n <= 0return;
 
    int res = n % 2;
    if (res == 1) binary[cnt] = '1';
    else binary[cnt] = '0';
    cnt++;
 
    func(n / 2);
}
 
int main(void) {
    cin.sync_with_stdio(false);
 
    int n;
    cin >> n;
 
    func(n);
    
    if (!binary[0]) binary[0= '0';
 
    string res = binary;
    reverse(res.begin(), res.end());
    cout << res;
}
cs

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형

'IT > Algorithm' 카테고리의 다른 글

정렬 - K번째 수  (0) 2020.11.15
우선순위 큐, 그리디 - 허프만 압축  (0) 2020.11.12
완전 탐색 - 소수 찾기  (0) 2020.09.03
DFS - 타겟 넘버  (0) 2020.09.01
무식하게 풀기(완전 탐색) - 모의고사  (0) 2020.08.31

댓글