藍橋杯 基礎練習 十六進位轉八進位 【字串處理】

來源:互聯網
上載者:User

標籤:字串

  基礎練習 十六進位轉八進位  時間限制: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;}


 

 

藍橋杯 基礎練習 十六進位轉八進位 【字串處理】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.