[백준 1212] 8진수 2진수 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
입력으로 주어진 8진수 수를 2진수로 변환하는 문제입니다.
접근법
- 각 8진수 자릿수는 3자리 이진수로 변환됩니다.
- 따라서 입력된 문자열을 앞에서부터 한 자리씩 읽고,
각 자리 값을 이진수 3자리로 바꾸면 됩니다. - 단, 가장 앞자리의 경우에는 앞에 붙는 0을 생략해야 하므로,
변환된 이진수의
앞부분에 포함된 0
을 제거한 뒤 출력합니다. - 수가
0
하나만 주어진 경우를 제외하고는 반드시1
로 시작해야 합니다.
Code
C#
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
using System;
using System.Text;
class Program {
static void Main() {
string s = Console.ReadLine();
var sb = new StringBuilder();
for (int i = 0; i < s.Length; i++) {
int n = s[i] - '0';
string bin = "";
if (i == 0) {
while (n > 0) {
bin = (n % 2) + bin;
n /= 2;
}
if (bin == "") bin = "0";
} else {
for (int j = 2; j >= 0; j--)
bin += (n >> j & 1);
}
sb.Append(bin);
}
Console.WriteLine(sb.ToString());
}
}
C++
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
#include <bits/stdc++.h>
using namespace std;
string toBin(int n) {
string s;
for (int i = 2; i >= 0; i--)
s += (n >> i & 1) + '0';
return s;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s; cin >> s;
for (size_t i = 0; i < s.size(); i++) {
string t = toBin(s[i] - '0');
if (i == 0) {
size_t j = 0;
while (j < 2 && t[j] == '0') j++;
t = t.substr(j);
}
cout << t;
}
cout << "\n";
return 0;
}