1 /* 2 * input: an expression seperated by a '-' or '+'; for example: a-b, a+b 3 * ouput: the answer of the input expression 4 */ 5 #include6 #include 7 8 #define MAX_N 205 9 10 char a[MAX_N], b[MAX_N], ans[MAX_N]; 11 char op; 12 13 void reverse(char *s) { 14 size_t len = strlen(s); 15 size_t i; 16 17 for (i = 0; i < (len>>1); i++) { 18 s[i] ^= s[len-i-1]; 19 s[len-i-1] ^= s[i]; 20 s[i] ^= s[len-i-1]; 21 } 22 } 23 24 void balance(char *a, char *b) { 25 size_t len_a = strlen(a); 26 size_t len_b = strlen(b); 27 28 while (len_a < len_b) { 29 a[len_a++] = '0'; 30 a[len_a] = '\0'; 31 } 32 while (len_b < len_a) { 33 b[len_b++] = '0'; 34 b[len_b] = '\0'; 35 } 36 } 37 38 void reduce(char *s) { 39 size_t len = strlen(s); 40 41 while (len > 1 && s[len-1] == '0') len--; 42 s[len] = '\0'; 43 } 44 45 void add(char *res, char *a, char *b) { 46 reverse(a); 47 reverse(b); 48 balance(a, b); 49 50 size_t n = strlen(a); 51 size_t i; 52 int c = 0, x; 53 char s[MAX_N]; 54 55 for (i = 0; i < n; i++) { 56 x = (a[i] - '0') + (b[i] - '0') + c; 57 c = x / 10; 58 s[i] = x % 10 + '0'; 59 } 60 if (c > 0) s[i++] = c + '0'; 61 s[i] = '\0'; 62 63 reduce(a); 64 reduce(b); 65 reverse(a); 66 reverse(b); 67 reverse(s); 68 69 strcpy(res, s); 70 } 71 72 void sub(char *res, char *a, char *b) { 73 if (strlen(a) < strlen(b) || (strlen(a) == strlen(b) && strcmp(a, b) < 0)) { 74 res[0] = '-'; 75 sub(res+1, b, a); 76 return ; 77 } 78 79 reverse(a); 80 reverse(b); 81 balance(a, b); 82 83 char s[MAX_N]; 84 size_t n = strlen(a); 85 size_t i; 86 87 int c = 0, x; 88 for (i = 0; i < n; i++) { 89 x = a[i] - b[i] - c; 90 c = 0; 91 if (x < 0) { 92 x += 10; 93 c = 1; 94 } 95 s[i] = x + '0'; 96 } 97 98 s[n] = '\0'; 99 100 reduce(s);101 reduce(b);102 reverse(a);103 reverse(b);104 reverse(s);105 strcpy(res, s);106 }107 108 void input() {109 char s[MAX_N];110 scanf("%s", s);111 112 size_t len = strlen(s);113 size_t i;114 for (i = 0; i < len; i++) 115 if (s[i] != '-' && s[i] != '+') a[i] = s[i];116 else break;117 a[i] = '\0';118 119 op = s[i];120 121 strcpy(b, s+i+1);122 }123 124 void output() {125 if (op == '-') 126 sub(ans, a, b);127 else128 add(ans, a, b);129 puts(ans);130 }131 132 int main(void) {133 int T;134 scanf("%d", &T);135 while ( T-->0) {136 input(); 137 output();138 }139 140 return 0;141 }