※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※
이번에 볼 문제는 백준 6040번 문제인 Hexadecimal Conversion이다.
문제는 아래 링크를 확인하자.
https://www.acmicpc.net/problem/6040
6040번: Hexadecimal Conversion
Bessie was teaching Jessie, her protege interesting in programming contests the binary facts of life. She explained that computers work in binary (base 2) and that all computer numbers in general are stored as 0's and 1's. Jessie was a bit unclear on the c
www.acmicpc.net
16진수는 뒤에서부터 세 자리씩 끊어 해당 수를 네 자리 8진수로 각각 변환하는 것으로 8진수로 변환 가능하다.
자릿수를 3의 배수로 맞추기 위해 16진수의 앞에 leading zero를 채워넣고 반복문을 이용해 16진수를 세자리씩 끊어 계산해주자.
단, 변환된 8진수를 출력할 때 leading zero를 출력하지 않게끔 주의하자.
아래는 제출한 소스코드이다.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string s, ans;
int arr[128];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
arr['0'] = 0, arr['1'] = 1, arr['2'] = 2, arr['3'] = 3, arr['4'] = 4, arr['5'] = 5, arr['6'] = 6, arr['7'] = 7, arr['8'] = 8, arr['9'] = 9, arr['A'] = 10, arr['B'] = 11, arr['C'] = 12, arr['D'] = 13, arr['E'] = 14, arr['F'] = 15;
cin >> s;
if (s == "0") {
cout << 0;
return 0;
}
while (s.length() % 3) s = "0" + s;
int slen = s.length();
for (int i = 0; i < slen; i += 3) {
int num = 0;
for (int j = 0; j < 3; j++) {
num *= 16;
num += arr[s[i + j]];
}
string tmp = "";
for (int i = 0; i < 4; i++) {
tmp += (char)((num % 8) + '0');
num /= 8;
}
reverse(tmp.begin(), tmp.end());
ans += tmp;
}
int idx = 0, anslen = ans.length();
while (ans[idx] == '0') idx++;
for (; idx < anslen; idx++) cout << ans[idx];
}
728x90
'BOJ' 카테고리의 다른 글
[BOJ 25044 // C++] 에어컨 (0) | 2022.10.02 |
---|---|
[BOJ 14911 // C++] 궁합 쌍 찾기 (1) | 2022.10.01 |
[BOJ 14915 // C++] 진수 변환기 (0) | 2022.09.29 |
[BOJ 1233 // C++] 주사위 (0) | 2022.09.28 |
[BOJ 6060 // C++] Wheel Rotation (0) | 2022.09.27 |