问题描述
给定n个十六进制正整数,输出它们对应的八进制数。
输入格式
输入的第一行为一个正整数n (1<=n<=10)。
接下来n行,每行一个由0~9、大写字母A~F组成的字符串,表示要转换的十六进制正整数,每个十六进制数长度不超过100000。
接下来n行,每行一个由0~9、大写字母A~F组成的字符串,表示要转换的十六进制正整数,每个十六进制数长度不超过100000。
输出格式
输出n行,每行为输入对应的八进制正整数。
注意
输入的十六进制数不会有前导0,比如012A。
输出的八进制数也不能有前导0。
输出的八进制数也不能有前导0。
样例输入
2
39
123ABC
39
123ABC
样例输出
71
4435274
4435274
#include<memory>
#include<iostream>
#include<string>
#include<cctype>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<cstdlib>
#include<cstdio>
#include<sstream>
using namespace std;
bool to16_2(std::string& to_two ){
std::string word = to_two;
to_two.clear ();
for (unsigned int var1 = 0; var1 < word.length (); ++var1) {
switch (word.at (var1)) {
case 'A':
to_two += "1010";
break;
case 'B':
to_two += "1011";
break;
case 'C':
to_two += "1100";
break;
case 'D':
to_two += "1101";
break;
case 'E':
to_two += "1110";
break;
case 'F':
to_two += "1111";
break;
case '0':
to_two += "0000";
break;
case '1':
to_two += "0001";
break;
case '2':
to_two += "0010";
break;
case '3':
to_two += "0011";
break;
case '4':
to_two += "0100";
break;
case '5':
to_two += "0101";
break;
case '6':
to_two += "0110";
break;
case '7':
to_two += "0111";
break;
case '8':
to_two += "1000";
break;
case '9':
to_two += "1001";
break;
default:
return false;
break;
}
}
// cout << to_two <<endl;
return true;
}
bool to2_8(std::string& word){
std::string to_eight = word;
word.clear ();
int need = to_eight.length ()% 3;
switch (need) {
case 0:
break;
case 1:
to_eight = "00" + to_eight;
break;
case 2:
to_eight = "0" + to_eight;
break;
default:
return false;
break;
}
std::stringstream ss;
int a = 0;
for (unsigned int var = 0; var < to_eight.length (); var = var + 3 ) {
a = (to_eight.at (var) - '0')*4 + (to_eight.at (var+1) - '0')*2 + (to_eight.at (var+2) - '0')*1;
if (!var && !a) {
continue;
}
// cout <<a;
ss << a;
word = ss.str ();
}
cout << endl;
return true;
}
int main(int argc, char *argv[])
{
int n = 0;
string word;
cin >> n;
for (int var = 0; var < n; ++var) {
cin >> word;
to16_2 (word);
//cout << word <<endl;
to2_8 (word);
cout <<word <<endl;
}
return 0;
}