原題: https://www.patest.cn/contests/pat-b-practise/1074
思路: 就是人工模擬加法的問題, 正常進制都是10, 現在就是進制從字符串中
讀取. 但有些情況要坐下特殊處理, 比如輸入的兩個數可能位數不一樣, 這對
我們后續計算造成不小的麻煩, 我的做法是強制補前導0, 使輸入完全一致.
另外需要注意兩個3位數相加可能得到4位數, 所以結果字符串要開大一些. 題目
中給的數字范圍都沒什么暖用, 比如題目中說了輸入的兩個數是正的, 但結果測試
仍然會檢查輸出為0的情況, 試問兩個正數相加怎么能得0呢, 但是我們實現的算法
不管有沒有0, 都能正常工作.
題目中有個數字是有用的, 那就是數字的位數為20位, 這就要求在后續打印數字的
時候不能采用sscanf
進行字符串轉數字. 只能采用傳統的方法使用getchar
一步
打印
測試點3和測試點4測試的是數非常大的情況, 比如20位
測試點5測試的是輸出0的情況
實現:
#include <stdio.h>
#include <string.h>
#define LEN 30
int main (void) {
char table[LEN];
int len;
char num1[LEN];
char num2[LEN];
char res[LEN];
char tmp1[LEN];
char tmp2[LEN];
int i;
int j;
table[0] = '0';
scanf("%s", table + 1);
scanf("%s", tmp1);
scanf("%s", tmp2);
len = strlen(table);
for (i = 0; i < len; i++) {
num1[i] = '0';
num2[i] = '0';
res[i] = '0';
}
i = len - 1;
for (j = strlen(tmp1) - 1; j >= 0; j--) num1[i--] = tmp1[j];
num1[len] = '\0'; // 這個不能少
i = len - 1;
for (j = strlen(tmp2) - 1; j >= 0; j--) num2[i--] = tmp2[j];
num2[len] = '\0';
int now;
int carry = 0; // 進位
int sys; // 進制
for (i = len - 1; i >= 0; i--) {
if (table[i] == '0') {
sys = 10;
} else {
sys = table[i] - '0';
}
now = (num1[i] - '0') + (num2[i] - '0') + carry;
if (now < sys) {
res[i] = now + '0';
carry = 0;
} else {
carry = 1;
res[i] = now - sys + '0';
}
}
res[len] = '\0'; // 這行也可以不需要
for (i = 0; i < len; i++) {
if (res[i] != '0') break;
}
if (i == len) {
printf("0");
} else {
for (; i < len; i++) {
printf("%c", res[i]);
}
}
return 0;
}