想法:
先不考慮進位與不夠減的情況,把每個位數都加起來,最後再處理進位或借位。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstring> | |
using namespace std; | |
int main() | |
{ | |
char num[101][1001]; | |
int ans[1001]={0}; | |
for (int i = 0; scanf("%s",num[i]); i++){ | |
if (num[i][0] == '0') break; | |
if (num[i][0] != '-'){ // 正數輸入 | |
for (int j = strlen(num[i])-1, k = 0; j >= 0; j--, k++) | |
ans[k] += (num[i][j] - '0'); | |
} | |
else { // 負數輸入 | |
for (int j = strlen(num[i])-1, k = 0; j >= 1; j--, k++) | |
ans[k] -= (num[i][j] - '0'); | |
} | |
} | |
bool negative = 0; | |
int i = 1000; | |
while (ans[i] == 0) i--; // 找答案的最高位數 | |
if (ans[i] < 0) negative = 1; | |
if (negative) // 如果答案為負數,先將每個數字變號,確保最高位數為正 | |
for (int j = 0; j <= i; j++) ans[j] *= (-1); | |
for (int j = 0; j <= i; j++){ | |
int k = j; | |
while (ans[k] > 9){ // 一直往高位數進位,直到不能進位為止 | |
ans[k+1]++; | |
ans[k] -= 10; | |
if (ans[k] <= 9) k++; // 確保該位數<=9 | |
} | |
while (ans[k] < 0){ // 一直向高位數拿10,來使該位數>=0 | |
ans[k+1]--; | |
ans[k] += 10; | |
if (ans[k] >= 0) k++; // 確保該位數>=0 | |
} | |
} | |
if (negative) printf("-"); | |
for (i = 1000; ans[i] == 0; i--); // 因為進位的關係,重新找最高位數 | |
for (; i >= 0; i--) | |
printf("%d", ans[i]); | |
printf("\n"); | |
return 0; | |
} |
沒有留言:
張貼留言