1. 程式人生 > 其它 >107 16進位制加法

107 16進位制加法

問題描述 :

某天、小晨在路上揹著單詞,突遇一外星人,外星人對小晨很感興趣,為了考驗小晨的智商,就向小晨提問簡單加法,由於外星人使用16進位制,所以,小晨必須用16進位制回答。

 

輸入說明 :

首先輸入一個整數T,

以下T行,每行兩個16進位制數字

輸出說明 :

T行,每行一個16進位制數,為求出的兩數之和。

其中的英文字母a到f為小寫。

輸入範例 :

2
4b0d 4887
2745 7438

輸出範例 :

9394
9b7d

思想:和上題一樣,改一下進位判斷條件和處理a-f和0-9的asc碼的方法即可。

#include <stdio.h>
#include <string
.h> int main() { int num, i, j, k; scanf("%d", &num); for (k = 0; k < num; k++) { char n[4000]; char num1[2000]; int count1 = 0; char num2[2000]; int count2 = 0; char res[3000]; int count3 = 0; if(k==0){ getchar();
//首行輸入 吸收一下回車 } gets(n); int flag = 0; //進位標誌 for (i = 0; i < strlen(n); i++) //第一個數字 { if (n[i] != ' ') { num1[count1++] = n[i]; } else { i++; break; } }
for (; i < strlen(n); i++) //第二個數字 { if(n[i]==' '){ // oj給的最後一個算例 調了一個小時沒找到問題在哪 原來是它輸入不規範 第二個數後面有空格 給它特殊處理一下 break; } num2[count2++] = n[i]; if(n[i]==' '){ break; } } count1--; //count指向了後一個數 所以還原一下 count2--; while (count1>=0 && count2>=0) //進行加法 { int a ,b; if(num1[count1]>='a'&&num1[count1]<='f'){ a = num1[count1] - 87; count1--; }else{ a = num1[count1] - '0'; count1--; } if(num2[count2]>='a'&&num2[count2]<='f'){ b = num2[count2] - 87; count2--; }else{ b = num2[count2] - '0'; count2--; } int temp = a + b + flag; flag = 0; if (temp >= 16) { flag = temp/16; temp %= 16; } if(temp>=10&&temp<16){ temp = temp+87; }else{ temp = temp+'0'; } res[count3++] = temp; } if (count1==-1 && count2==-1 && flag) //如果兩個數都加完了,還往前進一位的情況 { res[count3++] = flag+'0'; } else { while (count1>=0) //1數的高位 累加進位處理 { int temp; if(num1[count1]>='a'&&num1[count1]<='f'){ temp = num1[count1--] - 87 + flag; }else{ temp = num1[count1--] - '0' + flag; } flag = 0; if (temp >= 16) { flag = temp/16; temp %= 16; } if (temp>=10&&temp<16){ temp = temp +87; }else{ temp = temp +'0'; } res[count3++] = temp; } while (count2>=0) //2數的高位 累加進位處理 { int temp; if(num2[count2]>='a'&&num2[count2]<='f'){ temp = num2[count2--] - 87 + flag; }else{ temp = num2[count2--] - '0' + flag; } flag = 0; if (temp >= 16) { flag = temp/16; temp %= 16; } if (temp>=10&&temp<16){ temp = temp +87; }else{ temp = temp +'0'; } res[count3++] = temp; } } for (i = count3-1; i >=0; i--) { printf("%c", res[i]); } printf("\n"); } }