Created
February 7, 2014 08:57
-
-
Save KT-Yeh/8859321 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment