基础练习 十六进制转八进制
时间限制:1.0s 内存限制:512.0MB
问题描述
给定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 <stdio.h>
#include <string.h>
#define M 100005
char s[M*4];
char str[M];
int ans[150005];
int main(){
int n;
//char temp[6];
scanf("%d", &n);
while(n --){
scanf("%s", str+1);
memset(s, 0, sizeof(s));
int i, j, len = strlen(str+1)+1, temp;
// printf("%d..\n", len);
for(i = 1; i < len; ++i){
if(str[i] >= '0'&&str[i] <= '9'){
temp = str[i] - '0';
}
else temp = 10+str[i]-'A';
j = i*4;
while(temp){
s[j] = temp%2+'0';
j--;
temp /= 2;
}
while(j > (i-1)*4){
s[j--] = '0';
}
}
// printf("%s", &s[1]);
memset(ans, 0, sizeof(ans));
int tot = 0;
for(i = (len-1)*4; i-3 >= 0; i -= 3){
ans[tot++] = (s[i]-'0')+(s[i-1]-'0')*2+(s[i-2]-'0')*4;
}
temp = 1;
if(s[i] != '\0'){
++tot;
while(i > 0&&s[i]!='\0'){
ans[tot-1] += (s[i]-'0')*temp;
temp *= 2;
--i;
}
}
while(tot>0&&ans[tot] == 0) --tot;
for(i = tot; i >= 0; -- i) printf("%d", ans[i]);
puts("");
//
//for(i = ())
}
return 0;
}