標籤:字串
基礎練習 十六進位轉八進位 時間限制:1.0s 記憶體限制:512.0MB 問題描述 給定n個十六進位正整數,輸出它們對應的八位元。輸入格式 輸入的第一行為一個正整數n (1<=n<=10)。
接下來n行,每行一個由0~9、大寫字母A~F組成的字串,表示要轉換的十六進位正整數,每個十六進位數長度不超過100000。輸出格式 輸出n行,每行為輸入對應的八進位正整數。注意 輸入的十六進位數不會有前置0,比如012A。
輸出的八位元也不能有前置0。範例輸入2
39
123ABC範例輸出71
4435274提示 先將十六進位數轉換成某進位數,再由某進位數轉換成八進位。
思路:先轉化為二進位再轉化為八進位
代碼:
#include <stdio.h>#include <string.h>#define M 100005char 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;}
藍橋杯 基礎練習 十六進位轉八進位 【字串處理】